From 07618fe6d75b282d7df2c582ef76c3b2cdb820c0 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Mon, 10 Nov 2025 17:50:49 +0000 Subject: [PATCH 1/3] feat: update image to us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-librarian-generator@sha256:c8612d3fffb3f6a32353b2d1abd16b61e87811866f7ec9d65b59b02eb452a620 --- .librarian/state.yaml | 2 +- .../grafeas/grafeas/grafeas/gapic_version.py | 16 - .../grafeas/grafeas/grafeas_v1/__init__.py | 228 - .../grafeas/grafeas_v1/gapic_metadata.json | 238 - .../grafeas/grafeas_v1/gapic_version.py | 16 - packages/grafeas/grafeas/grafeas_v1/py.typed | 2 - .../grafeas/grafeas_v1/services/__init__.py | 15 - .../grafeas_v1/services/grafeas/__init__.py | 22 - .../services/grafeas/async_client.py | 1848 --- .../grafeas_v1/services/grafeas/client.py | 1970 --- .../grafeas_v1/services/grafeas/pagers.py | 509 - .../services/grafeas/transports/README.rst | 9 - .../services/grafeas/transports/__init__.py | 36 - .../services/grafeas/transports/base.py | 435 - .../services/grafeas/transports/grpc.py | 715 - .../grafeas/transports/grpc_asyncio.py | 895 -- .../services/grafeas/transports/rest.py | 3034 ---- .../services/grafeas/transports/rest_base.py | 874 - .../grafeas/grafeas_v1/types/__init__.py | 215 - .../grafeas/grafeas_v1/types/attestation.py | 147 - .../grafeas/grafeas/grafeas_v1/types/build.py | 114 - .../grafeas/grafeas_v1/types/common.py | 380 - .../grafeas/grafeas_v1/types/compliance.py | 214 - .../grafeas/grafeas/grafeas_v1/types/cvss.py | 465 - .../grafeas/grafeas_v1/types/deployment.py | 124 - .../grafeas/grafeas_v1/types/discovery.py | 283 - .../grafeas_v1/types/dsse_attestation.py | 100 - .../grafeas/grafeas_v1/types/grafeas.py | 941 -- .../grafeas/grafeas/grafeas_v1/types/image.py | 157 - .../grafeas_v1/types/intoto_provenance.py | 246 - .../grafeas_v1/types/intoto_statement.py | 362 - .../grafeas/grafeas_v1/types/package.py | 378 - .../grafeas/grafeas_v1/types/provenance.py | 596 - .../grafeas/grafeas/grafeas_v1/types/sbom.py | 169 - .../grafeas/grafeas_v1/types/secret.py | 154 - .../grafeas/grafeas_v1/types/severity.py | 55 - .../grafeas_v1/types/slsa_provenance.py | 256 - .../types/slsa_provenance_zero_two.py | 240 - .../grafeas/grafeas_v1/types/upgrade.py | 265 - .../grafeas/grafeas/grafeas_v1/types/vex.py | 390 - .../grafeas/grafeas_v1/types/vulnerability.py | 597 - packages/grafeas/mypy.ini | 3 - packages/grafeas/noxfile.py | 616 - ...erated_grafeas_batch_create_notes_async.py | 53 - ...nerated_grafeas_batch_create_notes_sync.py | 53 - ..._grafeas_batch_create_occurrences_async.py | 53 - ...d_grafeas_batch_create_occurrences_sync.py | 53 - ..._v1_generated_grafeas_create_note_async.py | 54 - ...s_v1_generated_grafeas_create_note_sync.py | 54 - ...nerated_grafeas_create_occurrence_async.py | 53 - ...enerated_grafeas_create_occurrence_sync.py | 53 - ..._v1_generated_grafeas_delete_note_async.py | 50 - ...s_v1_generated_grafeas_delete_note_sync.py | 50 - ...nerated_grafeas_delete_occurrence_async.py | 50 - ...enerated_grafeas_delete_occurrence_sync.py | 50 - ...sis_v1_generated_grafeas_get_note_async.py | 53 - ...ysis_v1_generated_grafeas_get_note_sync.py | 53 - ..._generated_grafeas_get_occurrence_async.py | 53 - ...rated_grafeas_get_occurrence_note_async.py | 53 - ...erated_grafeas_get_occurrence_note_sync.py | 53 - ...1_generated_grafeas_get_occurrence_sync.py | 53 - ...ted_grafeas_list_note_occurrences_async.py | 54 - ...ated_grafeas_list_note_occurrences_sync.py | 54 - ...s_v1_generated_grafeas_list_notes_async.py | 54 - ...is_v1_generated_grafeas_list_notes_sync.py | 54 - ...enerated_grafeas_list_occurrences_async.py | 54 - ...generated_grafeas_list_occurrences_sync.py | 54 - ..._v1_generated_grafeas_update_note_async.py | 53 - ...s_v1_generated_grafeas_update_note_sync.py | 53 - ...nerated_grafeas_update_occurrence_async.py | 53 - ...enerated_grafeas_update_occurrence_sync.py | 53 - .../snippet_metadata_grafeas.v1.json | 2353 --- .../scripts/fixup_grafeas_v1_keywords.py | 189 - packages/grafeas/setup.py | 100 - packages/grafeas/testing/constraints-3.10.txt | 8 - packages/grafeas/testing/constraints-3.11.txt | 8 - packages/grafeas/testing/constraints-3.12.txt | 8 - packages/grafeas/testing/constraints-3.13.txt | 12 - packages/grafeas/testing/constraints-3.14.txt | 12 - packages/grafeas/testing/constraints-3.7.txt | 12 - packages/grafeas/testing/constraints-3.8.txt | 8 - packages/grafeas/testing/constraints-3.9.txt | 8 - packages/grafeas/tests/__init__.py | 15 - packages/grafeas/tests/unit/__init__.py | 15 - packages/grafeas/tests/unit/gapic/__init__.py | 15 - .../tests/unit/gapic/grafeas_v1/__init__.py | 15 - .../unit/gapic/grafeas_v1/test_grafeas.py | 13188 ---------------- 87 files changed, 1 insertion(+), 35776 deletions(-) delete mode 100644 packages/grafeas/grafeas/grafeas/gapic_version.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/__init__.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json delete mode 100644 packages/grafeas/grafeas/grafeas_v1/gapic_version.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/py.typed delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/__init__.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/__init__.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/attestation.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/build.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/common.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/compliance.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/cvss.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/deployment.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/discovery.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/grafeas.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/image.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/package.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/provenance.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/sbom.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/secret.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/severity.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/upgrade.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/vex.py delete mode 100644 packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py delete mode 100644 packages/grafeas/mypy.ini delete mode 100644 packages/grafeas/noxfile.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py delete mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py delete mode 100644 packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json delete mode 100644 packages/grafeas/scripts/fixup_grafeas_v1_keywords.py delete mode 100644 packages/grafeas/setup.py delete mode 100644 packages/grafeas/testing/constraints-3.10.txt delete mode 100644 packages/grafeas/testing/constraints-3.11.txt delete mode 100644 packages/grafeas/testing/constraints-3.12.txt delete mode 100644 packages/grafeas/testing/constraints-3.13.txt delete mode 100644 packages/grafeas/testing/constraints-3.14.txt delete mode 100644 packages/grafeas/testing/constraints-3.7.txt delete mode 100644 packages/grafeas/testing/constraints-3.8.txt delete mode 100644 packages/grafeas/testing/constraints-3.9.txt delete mode 100644 packages/grafeas/tests/__init__.py delete mode 100644 packages/grafeas/tests/unit/__init__.py delete mode 100644 packages/grafeas/tests/unit/gapic/__init__.py delete mode 100644 packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py delete mode 100644 packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py diff --git a/.librarian/state.yaml b/.librarian/state.yaml index f35d6d501354..3441e6041b87 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -1,4 +1,4 @@ -image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-librarian-generator@sha256:39628f6e89c9cad27973b9a39a50f7052bec0435ee58c7027b4fa6b655943e31 +image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-librarian-generator@sha256:c8612d3fffb3f6a32353b2d1abd16b61e87811866f7ec9d65b59b02eb452a620 libraries: - id: google-ads-admanager version: 0.6.0 diff --git a/packages/grafeas/grafeas/grafeas/gapic_version.py b/packages/grafeas/grafeas/grafeas/gapic_version.py deleted file mode 100644 index f2979c0fa4af..000000000000 --- a/packages/grafeas/grafeas/grafeas/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -__version__ = "1.16.0" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/__init__.py b/packages/grafeas/grafeas/grafeas_v1/__init__.py deleted file mode 100644 index f58b3d96a6bb..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/__init__.py +++ /dev/null @@ -1,228 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 grafeas.grafeas_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.grafeas import GrafeasAsyncClient, GrafeasClient -from .types.attestation import AttestationNote, AttestationOccurrence, Jwt -from .types.build import BuildNote, BuildOccurrence -from .types.common import ( - BaseImage, - Digest, - Envelope, - EnvelopeSignature, - FileLocation, - LayerDetails, - License, - NoteKind, - RelatedUrl, - Signature, -) -from .types.compliance import ( - ComplianceNote, - ComplianceOccurrence, - ComplianceVersion, - NonCompliantFile, -) -from .types.cvss import CVSS, CVSSv3, CVSSVersion -from .types.deployment import DeploymentNote, DeploymentOccurrence -from .types.discovery import DiscoveryNote, DiscoveryOccurrence -from .types.dsse_attestation import DSSEAttestationNote, DSSEAttestationOccurrence -from .types.grafeas import ( - BatchCreateNotesRequest, - BatchCreateNotesResponse, - BatchCreateOccurrencesRequest, - BatchCreateOccurrencesResponse, - CreateNoteRequest, - CreateOccurrenceRequest, - DeleteNoteRequest, - DeleteOccurrenceRequest, - GetNoteRequest, - GetOccurrenceNoteRequest, - GetOccurrenceRequest, - ListNoteOccurrencesRequest, - ListNoteOccurrencesResponse, - ListNotesRequest, - ListNotesResponse, - ListOccurrencesRequest, - ListOccurrencesResponse, - Note, - Occurrence, - UpdateNoteRequest, - UpdateOccurrenceRequest, -) -from .types.image import Fingerprint, ImageNote, ImageOccurrence, Layer -from .types.intoto_provenance import ( - BuilderConfig, - Completeness, - InTotoProvenance, - Metadata, - Recipe, -) -from .types.intoto_statement import InTotoSlsaProvenanceV1, InTotoStatement, Subject -from .types.package import ( - Architecture, - Distribution, - Location, - PackageNote, - PackageOccurrence, - Version, -) -from .types.provenance import ( - AliasContext, - Artifact, - BuildProvenance, - CloudRepoSourceContext, - Command, - FileHashes, - GerritSourceContext, - GitSourceContext, - Hash, - ProjectRepoId, - RepoId, - Source, - SourceContext, -) -from .types.sbom import ( - SbomReferenceIntotoPayload, - SbomReferenceIntotoPredicate, - SBOMReferenceNote, - SBOMReferenceOccurrence, -) -from .types.secret import ( - SecretKind, - SecretLocation, - SecretNote, - SecretOccurrence, - SecretStatus, -) -from .types.severity import Severity -from .types.slsa_provenance import SlsaProvenance -from .types.slsa_provenance_zero_two import SlsaProvenanceZeroTwo -from .types.upgrade import ( - UpgradeDistribution, - UpgradeNote, - UpgradeOccurrence, - WindowsUpdate, -) -from .types.vex import VulnerabilityAssessmentNote -from .types.vulnerability import VulnerabilityNote, VulnerabilityOccurrence - -__all__ = ( - "GrafeasAsyncClient", - "AliasContext", - "Architecture", - "Artifact", - "AttestationNote", - "AttestationOccurrence", - "BaseImage", - "BatchCreateNotesRequest", - "BatchCreateNotesResponse", - "BatchCreateOccurrencesRequest", - "BatchCreateOccurrencesResponse", - "BuildNote", - "BuildOccurrence", - "BuildProvenance", - "BuilderConfig", - "CVSS", - "CVSSVersion", - "CVSSv3", - "CloudRepoSourceContext", - "Command", - "Completeness", - "ComplianceNote", - "ComplianceOccurrence", - "ComplianceVersion", - "CreateNoteRequest", - "CreateOccurrenceRequest", - "DSSEAttestationNote", - "DSSEAttestationOccurrence", - "DeleteNoteRequest", - "DeleteOccurrenceRequest", - "DeploymentNote", - "DeploymentOccurrence", - "Digest", - "DiscoveryNote", - "DiscoveryOccurrence", - "Distribution", - "Envelope", - "EnvelopeSignature", - "FileHashes", - "FileLocation", - "Fingerprint", - "GerritSourceContext", - "GetNoteRequest", - "GetOccurrenceNoteRequest", - "GetOccurrenceRequest", - "GitSourceContext", - "GrafeasClient", - "Hash", - "ImageNote", - "ImageOccurrence", - "InTotoProvenance", - "InTotoSlsaProvenanceV1", - "InTotoStatement", - "Jwt", - "Layer", - "LayerDetails", - "License", - "ListNoteOccurrencesRequest", - "ListNoteOccurrencesResponse", - "ListNotesRequest", - "ListNotesResponse", - "ListOccurrencesRequest", - "ListOccurrencesResponse", - "Location", - "Metadata", - "NonCompliantFile", - "Note", - "NoteKind", - "Occurrence", - "PackageNote", - "PackageOccurrence", - "ProjectRepoId", - "Recipe", - "RelatedUrl", - "RepoId", - "SBOMReferenceNote", - "SBOMReferenceOccurrence", - "SbomReferenceIntotoPayload", - "SbomReferenceIntotoPredicate", - "SecretKind", - "SecretLocation", - "SecretNote", - "SecretOccurrence", - "SecretStatus", - "Severity", - "Signature", - "SlsaProvenance", - "SlsaProvenanceZeroTwo", - "Source", - "SourceContext", - "Subject", - "UpdateNoteRequest", - "UpdateOccurrenceRequest", - "UpgradeDistribution", - "UpgradeNote", - "UpgradeOccurrence", - "Version", - "VulnerabilityAssessmentNote", - "VulnerabilityNote", - "VulnerabilityOccurrence", - "WindowsUpdate", -) diff --git a/packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json b/packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json deleted file mode 100644 index ec505dda48a9..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json +++ /dev/null @@ -1,238 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "grafeas.grafeas_v1", - "protoPackage": "grafeas.v1", - "schema": "1.0", - "services": { - "Grafeas": { - "clients": { - "grpc": { - "libraryClient": "GrafeasClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - }, - "grpc-async": { - "libraryClient": "GrafeasAsyncClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - }, - "rest": { - "libraryClient": "GrafeasClient", - "rpcs": { - "BatchCreateNotes": { - "methods": [ - "batch_create_notes" - ] - }, - "BatchCreateOccurrences": { - "methods": [ - "batch_create_occurrences" - ] - }, - "CreateNote": { - "methods": [ - "create_note" - ] - }, - "CreateOccurrence": { - "methods": [ - "create_occurrence" - ] - }, - "DeleteNote": { - "methods": [ - "delete_note" - ] - }, - "DeleteOccurrence": { - "methods": [ - "delete_occurrence" - ] - }, - "GetNote": { - "methods": [ - "get_note" - ] - }, - "GetOccurrence": { - "methods": [ - "get_occurrence" - ] - }, - "GetOccurrenceNote": { - "methods": [ - "get_occurrence_note" - ] - }, - "ListNoteOccurrences": { - "methods": [ - "list_note_occurrences" - ] - }, - "ListNotes": { - "methods": [ - "list_notes" - ] - }, - "ListOccurrences": { - "methods": [ - "list_occurrences" - ] - }, - "UpdateNote": { - "methods": [ - "update_note" - ] - }, - "UpdateOccurrence": { - "methods": [ - "update_occurrence" - ] - } - } - } - } - } - } -} diff --git a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py deleted file mode 100644 index f2979c0fa4af..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -__version__ = "1.16.0" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/py.typed b/packages/grafeas/grafeas/grafeas_v1/py.typed deleted file mode 100644 index 49e8f71d60b7..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The grafeas package uses inline types. diff --git a/packages/grafeas/grafeas/grafeas_v1/services/__init__.py b/packages/grafeas/grafeas/grafeas_v1/services/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py deleted file mode 100644 index ce3f2668a5ae..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 .async_client import GrafeasAsyncClient -from .client import GrafeasClient - -__all__ = ( - "GrafeasClient", - "GrafeasAsyncClient", -) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py deleted file mode 100644 index f88c2f9f5c0f..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py +++ /dev/null @@ -1,1848 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import logging as std_logging -import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) - -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from grafeas.grafeas_v1 import gapic_version as package_version - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.types import ( - attestation, - build, - common, - compliance, - deployment, - discovery, - dsse_attestation, - grafeas, - image, - package, - sbom, - secret, - upgrade, - vex, - vulnerability, -) - -from .client import GrafeasClient -from .transports.base import DEFAULT_CLIENT_INFO, GrafeasTransport -from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport - -try: - from google.api_core import client_logging # type: ignore - - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class GrafeasAsyncClient: - """`Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - """ - - _client: GrafeasClient - - note_path = staticmethod(GrafeasClient.note_path) - parse_note_path = staticmethod(GrafeasClient.parse_note_path) - occurrence_path = staticmethod(GrafeasClient.occurrence_path) - parse_occurrence_path = staticmethod(GrafeasClient.parse_occurrence_path) - project_path = staticmethod(GrafeasClient.project_path) - parse_project_path = staticmethod(GrafeasClient.parse_project_path) - common_billing_account_path = staticmethod( - GrafeasClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - GrafeasClient.parse_common_billing_account_path - ) - common_folder_path = staticmethod(GrafeasClient.common_folder_path) - parse_common_folder_path = staticmethod(GrafeasClient.parse_common_folder_path) - common_organization_path = staticmethod(GrafeasClient.common_organization_path) - parse_common_organization_path = staticmethod( - GrafeasClient.parse_common_organization_path - ) - common_project_path = staticmethod(GrafeasClient.common_project_path) - parse_common_project_path = staticmethod(GrafeasClient.parse_common_project_path) - common_location_path = staticmethod(GrafeasClient.common_location_path) - parse_common_location_path = staticmethod(GrafeasClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - GrafeasAsyncClient: The constructed client. - """ - return GrafeasClient.from_service_account_info.__func__(GrafeasAsyncClient, info, *args, **kwargs) # type: ignore - - @property - def transport(self) -> GrafeasTransport: - """Returns the transport used by the client instance. - - Returns: - GrafeasTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = GrafeasClient.get_transport_class - - def __init__( - self, - *, - transport: Union[str, GrafeasTransport] = "grpc_asyncio", - credentials: Optional[ga_credentials.Credentials] = None, - ) -> None: - """Instantiate the grafeas client. - - Args: - transport (Union[str, ~.GrafeasTransport]): The - transport to use. - 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. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = GrafeasClient( - transport=transport, - credentials=credentials, - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER - _LOGGER.debug( - "Created client `grafeas_v1.GrafeasAsyncClient`.", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { - "serviceName": "grafeas.v1.Grafeas", - "credentialsType": None, - }, - ) - - async def get_occurrence( - self, - request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Gets the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]]): - The request object. Request to get an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceRequest): - request = grafeas.GetOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_occurrence - ] - - # 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_occurrences( - self, - request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListOccurrencesAsyncPager: - r"""Lists occurrences for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]]): - The request object. Request to list occurrences. - parent (:class:`str`): - The name of the project to list occurrences for in the - form of ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: - Response for listing occurrences. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListOccurrencesRequest): - request = grafeas.ListOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_occurrences - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListOccurrencesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_occurrence( - self, - request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - await client.delete_occurrence(request=request) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]]): - The request object. Request to delete an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteOccurrenceRequest): - request = grafeas.DeleteOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_occurrence - ] - - # 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 create_occurrence( - self, - request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Creates a new occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]]): - The request object. Request to create a new occurrence. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is - to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): - The occurrence to create. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, occurrence] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateOccurrenceRequest): - request = grafeas.CreateOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrence is not None: - request.occurrence = occurrence - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_occurrence - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_create_occurrences( - self, - request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Creates new occurrences in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]]): - The request object. Request to create occurrences in - batch. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences - are to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrences (:class:`MutableSequence[grafeas.grafeas_v1.types.Occurrence]`): - The occurrences to create. Max - allowed length is 1000. - - This corresponds to the ``occurrences`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, occurrences] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): - request = grafeas.BatchCreateOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrences: - request.occurrences.extend(occurrences) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_create_occurrences - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_occurrence( - self, - request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Updates the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.update_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]]): - The request object. Request to update an occurrence. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): - The updated occurrence. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name, occurrence, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateOccurrenceRequest): - request = grafeas.UpdateOccurrenceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if occurrence is not None: - request.occurrence = occurrence - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_occurrence - ] - - # 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_occurrence_note( - self, - request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]]): - The request object. Request to get the note to which the - specified occurrence is attached. - name (:class:`str`): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceNoteRequest): - request = grafeas.GetOccurrenceNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_occurrence_note - ] - - # 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_note( - self, - request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]]): - The request object. Request to get a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetNoteRequest): - request = grafeas.GetNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_note] - - # 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_notes( - self, - request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNotesAsyncPager: - r"""Lists notes for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]]): - The request object. Request to list notes. - parent (:class:`str`): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: - Response for listing notes. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNotesRequest): - request = grafeas.ListNotesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_notes - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNotesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_note( - self, - request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - await client.delete_note(request=request) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]]): - The request object. Request to delete a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteNoteRequest): - request = grafeas.DeleteNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_note - ] - - # 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 create_note( - self, - request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, - *, - parent: Optional[str] = None, - note_id: Optional[str] = None, - note: Optional[grafeas.Note] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Creates a new note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = await client.create_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]]): - The request object. Request to create a new note. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note_id (:class:`str`): - The ID to use for this note. - This corresponds to the ``note_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (:class:`grafeas.grafeas_v1.types.Note`): - The note to create. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, note_id, note] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateNoteRequest): - request = grafeas.CreateNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if note_id is not None: - request.note_id = note_id - if note is not None: - request.note = note - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_note - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_create_notes( - self, - request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - notes: Optional[MutableMapping[str, grafeas.Note]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Creates new notes in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_notes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]]): - The request object. Request to create notes in batch. - parent (:class:`str`): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to - be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notes (:class:`MutableMapping[str, grafeas.grafeas_v1.types.Note]`): - The notes to create. Max allowed - length is 1000. - - This corresponds to the ``notes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, notes] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateNotesRequest): - request = grafeas.BatchCreateNotesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - if notes: - request.notes.update(notes) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_create_notes - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_note( - self, - request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - note: Optional[grafeas.Note] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Updates the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.update_note(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]]): - The request object. Request to update a note. - name (:class:`str`): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (:class:`grafeas.grafeas_v1.types.Note`): - The updated note. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The fields to update. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name, note, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateNoteRequest): - request = grafeas.UpdateNoteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if note is not None: - request.note = note - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_note - ] - - # 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_note_occurrences( - self, - request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, - *, - name: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNoteOccurrencesAsyncPager: - r"""Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - async def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]]): - The request object. Request to list occurrences for a - note. - name (:class:`str`): - The name of the note to list occurrences for in the form - of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The filter expression. - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: - Response for listing occurrences for - a note. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNoteOccurrencesRequest): - request = grafeas.ListNoteOccurrencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_note_occurrences - ] - - # 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNoteOccurrencesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "GrafeasAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ("GrafeasAsyncClient",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py deleted file mode 100644 index e286c84b8e18..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import warnings - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from grafeas.grafeas_v1 import gapic_version as package_version - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - -from grafeas.grafeas_v1.services.grafeas import pagers -from grafeas.grafeas_v1.types import ( - attestation, - build, - common, - compliance, - deployment, - discovery, - dsse_attestation, - grafeas, - image, - package, - sbom, - secret, - upgrade, - vex, - vulnerability, -) - -from .transports.base import DEFAULT_CLIENT_INFO, GrafeasTransport -from .transports.grpc import GrafeasGrpcTransport -from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport -from .transports.rest import GrafeasRestTransport - - -class GrafeasClientMeta(type): - """Metaclass for the Grafeas client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - - _transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] - _transport_registry["grpc"] = GrafeasGrpcTransport - _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport - _transport_registry["rest"] = GrafeasRestTransport - - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[GrafeasTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class GrafeasClient(metaclass=GrafeasClientMeta): - """`Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - GrafeasClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @property - def transport(self) -> GrafeasTransport: - """Returns the transport used by the client instance. - - Returns: - GrafeasTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def note_path( - project: str, - note: str, - ) -> str: - """Returns a fully-qualified note string.""" - return "projects/{project}/notes/{note}".format( - project=project, - note=note, - ) - - @staticmethod - def parse_note_path(path: str) -> Dict[str, str]: - """Parses a note path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/notes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def occurrence_path( - project: str, - occurrence: str, - ) -> str: - """Returns a fully-qualified occurrence string.""" - return "projects/{project}/occurrences/{occurrence}".format( - project=project, - occurrence=occurrence, - ) - - @staticmethod - def parse_occurrence_path(path: str) -> Dict[str, str]: - """Parses a occurrence path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/occurrences/(?P.+?)$", path - ) - return m.groupdict() if m else {} - - @staticmethod - def project_path( - project: str, - ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) - - @staticmethod - def parse_project_path(path: str) -> Dict[str, str]: - """Parses a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path( - folder: str, - ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path( - organization: str, - ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path( - project: str, - ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__( - self, - *, - transport: Union[str, GrafeasTransport] = None, - credentials: Optional[ga_credentials.Credentials] = None, - ) -> None: - """Instantiate the grafeas client. - - Args: - transport (Union[str, ~.GrafeasTransport]): The - transport to use. - 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. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - - if isinstance(transport, GrafeasTransport): - self._transport = transport - else: - Transport = GrafeasClient.get_transport_class(transport) - self._transport = Transport(credentials=credentials) - - def get_occurrence( - self, - request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Gets the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]): - The request object. Request to get an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceRequest): - request = grafeas.GetOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_occurrence] - - # 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_occurrences( - self, - request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListOccurrencesPager: - r"""Lists occurrences for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]): - The request object. Request to list occurrences. - parent (str): - The name of the project to list occurrences for in the - form of ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: - Response for listing occurrences. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListOccurrencesRequest): - request = grafeas.ListOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_occurrences] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListOccurrencesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_occurrence( - self, - request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - client.delete_occurrence(request=request) - - Args: - request (Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]): - The request object. Request to delete an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteOccurrenceRequest): - request = grafeas.DeleteOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_occurrence] - - # 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 create_occurrence( - self, - request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Creates a new occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]): - The request object. Request to create a new occurrence. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is - to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The occurrence to create. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, occurrence] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateOccurrenceRequest): - request = grafeas.CreateOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrence is not None: - request.occurrence = occurrence - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_occurrence] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_create_occurrences( - self, - request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, - *, - parent: Optional[str] = None, - occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Creates new occurrences in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]): - The request object. Request to create occurrences in - batch. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences - are to be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences to create. Max - allowed length is 1000. - - This corresponds to the ``occurrences`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, occurrences] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): - request = grafeas.BatchCreateOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if occurrences is not None: - request.occurrences = occurrences - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_occurrences] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_occurrence( - self, - request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, - *, - name: Optional[str] = None, - occurrence: Optional[grafeas.Occurrence] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Updates the specified occurrence. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.update_occurrence(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]): - The request object. Request to update an occurrence. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The updated occurrence. - This corresponds to the ``occurrence`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name, occurrence, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateOccurrenceRequest): - request = grafeas.UpdateOccurrenceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if occurrence is not None: - request.occurrence = occurrence - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_occurrence] - - # 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_occurrence_note( - self, - request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]): - The request object. Request to get the note to which the - specified occurrence is attached. - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetOccurrenceNoteRequest): - request = grafeas.GetOccurrenceNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_occurrence_note] - - # 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_note( - self, - request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Gets the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]): - The request object. Request to get a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.GetNoteRequest): - request = grafeas.GetNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_note] - - # 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_notes( - self, - request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNotesPager: - r"""Lists notes for the specified project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]): - The request object. Request to list notes. - parent (str): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: - Response for listing notes. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNotesRequest): - request = grafeas.ListNotesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_notes] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNotesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_note( - self, - request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - client.delete_note(request=request) - - Args: - request (Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]): - The request object. Request to delete a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.DeleteNoteRequest): - request = grafeas.DeleteNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_note] - - # 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 create_note( - self, - request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, - *, - parent: Optional[str] = None, - note_id: Optional[str] = None, - note: Optional[grafeas.Note] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Creates a new note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = client.create_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]): - The request object. Request to create a new note. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note_id (str): - The ID to use for this note. - This corresponds to the ``note_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (grafeas.grafeas_v1.types.Note): - The note to create. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, note_id, note] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.CreateNoteRequest): - request = grafeas.CreateNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if note_id is not None: - request.note_id = note_id - if note is not None: - request.note = note - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_note] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_create_notes( - self, - request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, - *, - parent: Optional[str] = None, - notes: Optional[MutableMapping[str, grafeas.Note]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Creates new notes in batch. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_notes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]): - The request object. Request to create notes in batch. - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to - be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): - The notes to create. Max allowed - length is 1000. - - This corresponds to the ``notes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, notes] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.BatchCreateNotesRequest): - request = grafeas.BatchCreateNotesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notes is not None: - request.notes = notes - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_notes] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_note( - self, - request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, - *, - name: Optional[str] = None, - note: Optional[grafeas.Note] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Updates the specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = client.update_note(request=request) - - # Handle the response - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]): - The request object. Request to update a note. - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - note (grafeas.grafeas_v1.types.Note): - The updated note. - This corresponds to the ``note`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.types.Note: - A type of analysis that can be done - for a resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name, note, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.UpdateNoteRequest): - request = grafeas.UpdateNoteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if note is not None: - request.note = note - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_note] - - # 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_note_occurrences( - self, - request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, - *, - name: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListNoteOccurrencesPager: - r"""Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from grafeas import grafeas_v1 - - def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]): - The request object. Request to list occurrences for a - note. - name (str): - The name of the note to list occurrences for in the form - of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The filter expression. - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: - Response for listing occurrences for - a note. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name, filter] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, grafeas.ListNoteOccurrencesRequest): - request = grafeas.ListNoteOccurrencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_note_occurrences] - - # 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNoteOccurrencesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "GrafeasClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ("GrafeasClient",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py deleted file mode 100644 index c062b968fcda..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py +++ /dev/null @@ -1,509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import ( - Any, - AsyncIterator, - Awaitable, - Callable, - Iterator, - Optional, - Sequence, - Tuple, - Union, -) - -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[ - retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None - ] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from grafeas.grafeas_v1.types import grafeas - - -class ListOccurrencesPager: - """A pager for iterating through ``list_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., grafeas.ListOccurrencesResponse], - request: grafeas.ListOccurrencesRequest, - response: grafeas.ListOccurrencesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListOccurrencesResponse): - The initial response object. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = grafeas.ListOccurrencesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[grafeas.ListOccurrencesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) - yield self._response - - def __iter__(self) -> Iterator[grafeas.Occurrence]: - for page in self.pages: - yield from page.occurrences - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListOccurrencesAsyncPager: - """A pager for iterating through ``list_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[grafeas.ListOccurrencesResponse]], - request: grafeas.ListOccurrencesRequest, - response: grafeas.ListOccurrencesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListOccurrencesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = grafeas.ListOccurrencesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[grafeas.ListOccurrencesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) - yield self._response - - def __aiter__(self) -> AsyncIterator[grafeas.Occurrence]: - async def async_generator(): - async for page in self.pages: - for response in page.occurrences: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNotesPager: - """A pager for iterating through ``list_notes`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotes`` requests and continue to iterate - through the ``notes`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., grafeas.ListNotesResponse], - request: grafeas.ListNotesRequest, - response: grafeas.ListNotesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNotesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNotesResponse): - The initial response object. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = grafeas.ListNotesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[grafeas.ListNotesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) - yield self._response - - def __iter__(self) -> Iterator[grafeas.Note]: - for page in self.pages: - yield from page.notes - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNotesAsyncPager: - """A pager for iterating through ``list_notes`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotes`` requests and continue to iterate - through the ``notes`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[grafeas.ListNotesResponse]], - request: grafeas.ListNotesRequest, - response: grafeas.ListNotesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNotesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNotesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = grafeas.ListNotesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[grafeas.ListNotesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) - yield self._response - - def __aiter__(self) -> AsyncIterator[grafeas.Note]: - async def async_generator(): - async for page in self.pages: - for response in page.notes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNoteOccurrencesPager: - """A pager for iterating through ``list_note_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNoteOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., grafeas.ListNoteOccurrencesResponse], - request: grafeas.ListNoteOccurrencesRequest, - response: grafeas.ListNoteOccurrencesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): - The initial response object. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = grafeas.ListNoteOccurrencesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[grafeas.ListNoteOccurrencesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) - yield self._response - - def __iter__(self) -> Iterator[grafeas.Occurrence]: - for page in self.pages: - yield from page.occurrences - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNoteOccurrencesAsyncPager: - """A pager for iterating through ``list_note_occurrences`` requests. - - This class thinly wraps an initial - :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``occurrences`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNoteOccurrences`` requests and continue to iterate - through the ``occurrences`` field on the - corresponding responses. - - All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[grafeas.ListNoteOccurrencesResponse]], - request: grafeas.ListNoteOccurrencesRequest, - response: grafeas.ListNoteOccurrencesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): - The initial request object. - response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = grafeas.ListNoteOccurrencesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[grafeas.ListNoteOccurrencesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) - yield self._response - - def __aiter__(self) -> AsyncIterator[grafeas.Occurrence]: - async def async_generator(): - async for page in self.pages: - for response in page.occurrences: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst deleted file mode 100644 index 1085202fe2c8..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`GrafeasTransport` is the ABC for all transports. -- public child `GrafeasGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `GrafeasGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseGrafeasRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `GrafeasRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py deleted file mode 100644 index 61a079d41d8b..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import GrafeasTransport -from .grpc import GrafeasGrpcTransport -from .grpc_asyncio import GrafeasGrpcAsyncIOTransport -from .rest import GrafeasRestInterceptor, GrafeasRestTransport - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] -_transport_registry["grpc"] = GrafeasGrpcTransport -_transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport -_transport_registry["rest"] = GrafeasRestTransport - -__all__ = ( - "GrafeasTransport", - "GrafeasGrpcTransport", - "GrafeasGrpcAsyncIOTransport", - "GrafeasRestTransport", - "GrafeasRestInterceptor", -) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py deleted file mode 100644 index f02e4dbde1cc..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py +++ /dev/null @@ -1,435 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -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.oauth2 import service_account # type: ignore -import google.protobuf -from google.protobuf import empty_pb2 # type: ignore - -from grafeas.grafeas_v1 import gapic_version as package_version -from grafeas.grafeas_v1.types import grafeas - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class GrafeasTransport(abc.ABC): - """Abstract transport class for Grafeas.""" - - AUTH_SCOPES = () - - DEFAULT_HOST: str = "" - - def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: ''). - 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]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_occurrence: gapic_v1.method.wrap_method( - self.get_occurrence, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_occurrences: gapic_v1.method.wrap_method( - self.list_occurrences, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_occurrence: gapic_v1.method.wrap_method( - self.delete_occurrence, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_occurrence: gapic_v1.method.wrap_method( - self.create_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_occurrences: gapic_v1.method.wrap_method( - self.batch_create_occurrences, - default_timeout=30.0, - client_info=client_info, - ), - self.update_occurrence: gapic_v1.method.wrap_method( - self.update_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.get_occurrence_note: gapic_v1.method.wrap_method( - self.get_occurrence_note, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_note: gapic_v1.method.wrap_method( - self.get_note, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_notes: gapic_v1.method.wrap_method( - self.list_notes, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_note: gapic_v1.method.wrap_method( - self.delete_note, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_note: gapic_v1.method.wrap_method( - self.create_note, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_notes: gapic_v1.method.wrap_method( - self.batch_create_notes, - default_timeout=30.0, - client_info=client_info, - ), - self.update_note: gapic_v1.method.wrap_method( - self.update_note, - default_timeout=30.0, - client_info=client_info, - ), - self.list_note_occurrences: gapic_v1.method.wrap_method( - self.list_note_occurrences, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def get_occurrence( - self, - ) -> Callable[ - [grafeas.GetOccurrenceRequest], - Union[grafeas.Occurrence, Awaitable[grafeas.Occurrence]], - ]: - raise NotImplementedError() - - @property - def list_occurrences( - self, - ) -> Callable[ - [grafeas.ListOccurrencesRequest], - Union[ - grafeas.ListOccurrencesResponse, Awaitable[grafeas.ListOccurrencesResponse] - ], - ]: - raise NotImplementedError() - - @property - def delete_occurrence( - self, - ) -> Callable[ - [grafeas.DeleteOccurrenceRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: - raise NotImplementedError() - - @property - def create_occurrence( - self, - ) -> Callable[ - [grafeas.CreateOccurrenceRequest], - Union[grafeas.Occurrence, Awaitable[grafeas.Occurrence]], - ]: - raise NotImplementedError() - - @property - def batch_create_occurrences( - self, - ) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - Union[ - grafeas.BatchCreateOccurrencesResponse, - Awaitable[grafeas.BatchCreateOccurrencesResponse], - ], - ]: - raise NotImplementedError() - - @property - def update_occurrence( - self, - ) -> Callable[ - [grafeas.UpdateOccurrenceRequest], - Union[grafeas.Occurrence, Awaitable[grafeas.Occurrence]], - ]: - raise NotImplementedError() - - @property - def get_occurrence_note( - self, - ) -> Callable[ - [grafeas.GetOccurrenceNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] - ]: - raise NotImplementedError() - - @property - def get_note( - self, - ) -> Callable[ - [grafeas.GetNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] - ]: - raise NotImplementedError() - - @property - def list_notes( - self, - ) -> Callable[ - [grafeas.ListNotesRequest], - Union[grafeas.ListNotesResponse, Awaitable[grafeas.ListNotesResponse]], - ]: - raise NotImplementedError() - - @property - def delete_note( - self, - ) -> Callable[ - [grafeas.DeleteNoteRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] - ]: - raise NotImplementedError() - - @property - def create_note( - self, - ) -> Callable[ - [grafeas.CreateNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] - ]: - raise NotImplementedError() - - @property - def batch_create_notes( - self, - ) -> Callable[ - [grafeas.BatchCreateNotesRequest], - Union[ - grafeas.BatchCreateNotesResponse, - Awaitable[grafeas.BatchCreateNotesResponse], - ], - ]: - raise NotImplementedError() - - @property - def update_note( - self, - ) -> Callable[ - [grafeas.UpdateNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] - ]: - raise NotImplementedError() - - @property - def list_note_occurrences( - self, - ) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - Union[ - grafeas.ListNoteOccurrencesResponse, - Awaitable[grafeas.ListNoteOccurrencesResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ("GrafeasTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py deleted file mode 100644 index 0424704ce4bf..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py +++ /dev/null @@ -1,715 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 json -import logging as std_logging -import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import gapic_v1, grpc_helpers -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.protobuf import empty_pb2 # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message -import grpc # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import grafeas - -from .base import DEFAULT_CLIENT_INFO, GrafeasTransport - -try: - from google.api_core import client_logging # type: ignore - - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class GrafeasGrpcTransport(GrafeasTransport): - """gRPC backend transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _stubs: Dict[str, Callable] - - def __init__( - self, - *, - host: str = "", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: ''). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel( - cls, - host: str = "", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs, - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" - return self._grpc_channel - - @property - def get_occurrence( - self, - ) -> Callable[[grafeas.GetOccurrenceRequest], grafeas.Occurrence]: - r"""Return a callable for the get occurrence method over gRPC. - - Gets the specified occurrence. - - Returns: - Callable[[~.GetOccurrenceRequest], - ~.Occurrence]: - 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_occurrence" not in self._stubs: - self._stubs["get_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/GetOccurrence", - request_serializer=grafeas.GetOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs["get_occurrence"] - - @property - def list_occurrences( - self, - ) -> Callable[[grafeas.ListOccurrencesRequest], grafeas.ListOccurrencesResponse]: - r"""Return a callable for the list occurrences method over gRPC. - - Lists occurrences for the specified project. - - Returns: - Callable[[~.ListOccurrencesRequest], - ~.ListOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_occurrences" not in self._stubs: - self._stubs["list_occurrences"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/ListOccurrences", - request_serializer=grafeas.ListOccurrencesRequest.serialize, - response_deserializer=grafeas.ListOccurrencesResponse.deserialize, - ) - return self._stubs["list_occurrences"] - - @property - def delete_occurrence( - self, - ) -> Callable[[grafeas.DeleteOccurrenceRequest], empty_pb2.Empty]: - r"""Return a callable for the delete occurrence method over gRPC. - - Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Returns: - Callable[[~.DeleteOccurrenceRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_occurrence" not in self._stubs: - self._stubs["delete_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/DeleteOccurrence", - request_serializer=grafeas.DeleteOccurrenceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs["delete_occurrence"] - - @property - def create_occurrence( - self, - ) -> Callable[[grafeas.CreateOccurrenceRequest], grafeas.Occurrence]: - r"""Return a callable for the create occurrence method over gRPC. - - Creates a new occurrence. - - Returns: - Callable[[~.CreateOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "create_occurrence" not in self._stubs: - self._stubs["create_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/CreateOccurrence", - request_serializer=grafeas.CreateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs["create_occurrence"] - - @property - def batch_create_occurrences( - self, - ) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], grafeas.BatchCreateOccurrencesResponse - ]: - r"""Return a callable for the batch create occurrences method over gRPC. - - Creates new occurrences in batch. - - Returns: - Callable[[~.BatchCreateOccurrencesRequest], - ~.BatchCreateOccurrencesResponse]: - 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 "batch_create_occurrences" not in self._stubs: - self._stubs["batch_create_occurrences"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/BatchCreateOccurrences", - request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, - response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, - ) - return self._stubs["batch_create_occurrences"] - - @property - def update_occurrence( - self, - ) -> Callable[[grafeas.UpdateOccurrenceRequest], grafeas.Occurrence]: - r"""Return a callable for the update occurrence method over gRPC. - - Updates the specified occurrence. - - Returns: - Callable[[~.UpdateOccurrenceRequest], - ~.Occurrence]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_occurrence" not in self._stubs: - self._stubs["update_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/UpdateOccurrence", - request_serializer=grafeas.UpdateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs["update_occurrence"] - - @property - def get_occurrence_note( - self, - ) -> Callable[[grafeas.GetOccurrenceNoteRequest], grafeas.Note]: - r"""Return a callable for the get occurrence note method over gRPC. - - Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Returns: - Callable[[~.GetOccurrenceNoteRequest], - ~.Note]: - 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_occurrence_note" not in self._stubs: - self._stubs["get_occurrence_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/GetOccurrenceNote", - request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["get_occurrence_note"] - - @property - def get_note(self) -> Callable[[grafeas.GetNoteRequest], grafeas.Note]: - r"""Return a callable for the get note method over gRPC. - - Gets the specified note. - - Returns: - Callable[[~.GetNoteRequest], - ~.Note]: - 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_note" not in self._stubs: - self._stubs["get_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/GetNote", - request_serializer=grafeas.GetNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["get_note"] - - @property - def list_notes( - self, - ) -> Callable[[grafeas.ListNotesRequest], grafeas.ListNotesResponse]: - r"""Return a callable for the list notes method over gRPC. - - Lists notes for the specified project. - - Returns: - Callable[[~.ListNotesRequest], - ~.ListNotesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_notes" not in self._stubs: - self._stubs["list_notes"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/ListNotes", - request_serializer=grafeas.ListNotesRequest.serialize, - response_deserializer=grafeas.ListNotesResponse.deserialize, - ) - return self._stubs["list_notes"] - - @property - def delete_note(self) -> Callable[[grafeas.DeleteNoteRequest], empty_pb2.Empty]: - r"""Return a callable for the delete note method over gRPC. - - Deletes the specified note. - - Returns: - Callable[[~.DeleteNoteRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_note" not in self._stubs: - self._stubs["delete_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/DeleteNote", - request_serializer=grafeas.DeleteNoteRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs["delete_note"] - - @property - def create_note(self) -> Callable[[grafeas.CreateNoteRequest], grafeas.Note]: - r"""Return a callable for the create note method over gRPC. - - Creates a new note. - - Returns: - Callable[[~.CreateNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "create_note" not in self._stubs: - self._stubs["create_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/CreateNote", - request_serializer=grafeas.CreateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["create_note"] - - @property - def batch_create_notes( - self, - ) -> Callable[[grafeas.BatchCreateNotesRequest], grafeas.BatchCreateNotesResponse]: - r"""Return a callable for the batch create notes method over gRPC. - - Creates new notes in batch. - - Returns: - Callable[[~.BatchCreateNotesRequest], - ~.BatchCreateNotesResponse]: - 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 "batch_create_notes" not in self._stubs: - self._stubs["batch_create_notes"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/BatchCreateNotes", - request_serializer=grafeas.BatchCreateNotesRequest.serialize, - response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, - ) - return self._stubs["batch_create_notes"] - - @property - def update_note(self) -> Callable[[grafeas.UpdateNoteRequest], grafeas.Note]: - r"""Return a callable for the update note method over gRPC. - - Updates the specified note. - - Returns: - Callable[[~.UpdateNoteRequest], - ~.Note]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_note" not in self._stubs: - self._stubs["update_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/UpdateNote", - request_serializer=grafeas.UpdateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["update_note"] - - @property - def list_note_occurrences( - self, - ) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], grafeas.ListNoteOccurrencesResponse - ]: - r"""Return a callable for the list note occurrences method over gRPC. - - Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Returns: - Callable[[~.ListNoteOccurrencesRequest], - ~.ListNoteOccurrencesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_note_occurrences" not in self._stubs: - self._stubs["list_note_occurrences"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/ListNoteOccurrences", - request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, - response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, - ) - return self._stubs["list_note_occurrences"] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ("GrafeasGrpcTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py deleted file mode 100644 index 63844b89b159..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py +++ /dev/null @@ -1,895 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 inspect -import json -import logging as std_logging -import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message -import grpc # type: ignore -from grpc.experimental import aio # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import grafeas - -from .base import DEFAULT_CLIENT_INFO, GrafeasTransport -from .grpc import GrafeasGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class GrafeasGrpcAsyncIOTransport(GrafeasTransport): - """gRPC AsyncIO backend transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel( - cls, - host: str = "", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be - removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: ''). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - This argument will be removed in the next major version of this library. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def get_occurrence( - self, - ) -> Callable[[grafeas.GetOccurrenceRequest], Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the get occurrence method over gRPC. - - Gets the specified occurrence. - - Returns: - Callable[[~.GetOccurrenceRequest], - Awaitable[~.Occurrence]]: - 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_occurrence" not in self._stubs: - self._stubs["get_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/GetOccurrence", - request_serializer=grafeas.GetOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs["get_occurrence"] - - @property - def list_occurrences( - self, - ) -> Callable[ - [grafeas.ListOccurrencesRequest], Awaitable[grafeas.ListOccurrencesResponse] - ]: - r"""Return a callable for the list occurrences method over gRPC. - - Lists occurrences for the specified project. - - Returns: - Callable[[~.ListOccurrencesRequest], - Awaitable[~.ListOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_occurrences" not in self._stubs: - self._stubs["list_occurrences"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/ListOccurrences", - request_serializer=grafeas.ListOccurrencesRequest.serialize, - response_deserializer=grafeas.ListOccurrencesResponse.deserialize, - ) - return self._stubs["list_occurrences"] - - @property - def delete_occurrence( - self, - ) -> Callable[[grafeas.DeleteOccurrenceRequest], Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete occurrence method over gRPC. - - Deletes the specified occurrence. For example, use - this method to delete an occurrence when the occurrence - is no longer applicable for the given resource. - - Returns: - Callable[[~.DeleteOccurrenceRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_occurrence" not in self._stubs: - self._stubs["delete_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/DeleteOccurrence", - request_serializer=grafeas.DeleteOccurrenceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs["delete_occurrence"] - - @property - def create_occurrence( - self, - ) -> Callable[[grafeas.CreateOccurrenceRequest], Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the create occurrence method over gRPC. - - Creates a new occurrence. - - Returns: - Callable[[~.CreateOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "create_occurrence" not in self._stubs: - self._stubs["create_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/CreateOccurrence", - request_serializer=grafeas.CreateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs["create_occurrence"] - - @property - def batch_create_occurrences( - self, - ) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], - Awaitable[grafeas.BatchCreateOccurrencesResponse], - ]: - r"""Return a callable for the batch create occurrences method over gRPC. - - Creates new occurrences in batch. - - Returns: - Callable[[~.BatchCreateOccurrencesRequest], - Awaitable[~.BatchCreateOccurrencesResponse]]: - 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 "batch_create_occurrences" not in self._stubs: - self._stubs["batch_create_occurrences"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/BatchCreateOccurrences", - request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, - response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, - ) - return self._stubs["batch_create_occurrences"] - - @property - def update_occurrence( - self, - ) -> Callable[[grafeas.UpdateOccurrenceRequest], Awaitable[grafeas.Occurrence]]: - r"""Return a callable for the update occurrence method over gRPC. - - Updates the specified occurrence. - - Returns: - Callable[[~.UpdateOccurrenceRequest], - Awaitable[~.Occurrence]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_occurrence" not in self._stubs: - self._stubs["update_occurrence"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/UpdateOccurrence", - request_serializer=grafeas.UpdateOccurrenceRequest.serialize, - response_deserializer=grafeas.Occurrence.deserialize, - ) - return self._stubs["update_occurrence"] - - @property - def get_occurrence_note( - self, - ) -> Callable[[grafeas.GetOccurrenceNoteRequest], Awaitable[grafeas.Note]]: - r"""Return a callable for the get occurrence note method over gRPC. - - Gets the note attached to the specified occurrence. - Consumer projects can use this method to get a note that - belongs to a provider project. - - Returns: - Callable[[~.GetOccurrenceNoteRequest], - Awaitable[~.Note]]: - 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_occurrence_note" not in self._stubs: - self._stubs["get_occurrence_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/GetOccurrenceNote", - request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["get_occurrence_note"] - - @property - def get_note(self) -> Callable[[grafeas.GetNoteRequest], Awaitable[grafeas.Note]]: - r"""Return a callable for the get note method over gRPC. - - Gets the specified note. - - Returns: - Callable[[~.GetNoteRequest], - Awaitable[~.Note]]: - 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_note" not in self._stubs: - self._stubs["get_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/GetNote", - request_serializer=grafeas.GetNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["get_note"] - - @property - def list_notes( - self, - ) -> Callable[[grafeas.ListNotesRequest], Awaitable[grafeas.ListNotesResponse]]: - r"""Return a callable for the list notes method over gRPC. - - Lists notes for the specified project. - - Returns: - Callable[[~.ListNotesRequest], - Awaitable[~.ListNotesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_notes" not in self._stubs: - self._stubs["list_notes"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/ListNotes", - request_serializer=grafeas.ListNotesRequest.serialize, - response_deserializer=grafeas.ListNotesResponse.deserialize, - ) - return self._stubs["list_notes"] - - @property - def delete_note( - self, - ) -> Callable[[grafeas.DeleteNoteRequest], Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete note method over gRPC. - - Deletes the specified note. - - Returns: - Callable[[~.DeleteNoteRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_note" not in self._stubs: - self._stubs["delete_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/DeleteNote", - request_serializer=grafeas.DeleteNoteRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs["delete_note"] - - @property - def create_note( - self, - ) -> Callable[[grafeas.CreateNoteRequest], Awaitable[grafeas.Note]]: - r"""Return a callable for the create note method over gRPC. - - Creates a new note. - - Returns: - Callable[[~.CreateNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "create_note" not in self._stubs: - self._stubs["create_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/CreateNote", - request_serializer=grafeas.CreateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["create_note"] - - @property - def batch_create_notes( - self, - ) -> Callable[ - [grafeas.BatchCreateNotesRequest], Awaitable[grafeas.BatchCreateNotesResponse] - ]: - r"""Return a callable for the batch create notes method over gRPC. - - Creates new notes in batch. - - Returns: - Callable[[~.BatchCreateNotesRequest], - Awaitable[~.BatchCreateNotesResponse]]: - 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 "batch_create_notes" not in self._stubs: - self._stubs["batch_create_notes"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/BatchCreateNotes", - request_serializer=grafeas.BatchCreateNotesRequest.serialize, - response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, - ) - return self._stubs["batch_create_notes"] - - @property - def update_note( - self, - ) -> Callable[[grafeas.UpdateNoteRequest], Awaitable[grafeas.Note]]: - r"""Return a callable for the update note method over gRPC. - - Updates the specified note. - - Returns: - Callable[[~.UpdateNoteRequest], - Awaitable[~.Note]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_note" not in self._stubs: - self._stubs["update_note"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/UpdateNote", - request_serializer=grafeas.UpdateNoteRequest.serialize, - response_deserializer=grafeas.Note.deserialize, - ) - return self._stubs["update_note"] - - @property - def list_note_occurrences( - self, - ) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], - Awaitable[grafeas.ListNoteOccurrencesResponse], - ]: - r"""Return a callable for the list note occurrences method over gRPC. - - Lists occurrences referencing the specified note. - Provider projects can use this method to get all - occurrences across consumer projects referencing the - specified note. - - Returns: - Callable[[~.ListNoteOccurrencesRequest], - Awaitable[~.ListNoteOccurrencesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_note_occurrences" not in self._stubs: - self._stubs["list_note_occurrences"] = self._logged_channel.unary_unary( - "/grafeas.v1.Grafeas/ListNoteOccurrences", - request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, - response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, - ) - return self._stubs["list_note_occurrences"] - - def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_occurrence: self._wrap_method( - self.get_occurrence, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_occurrences: self._wrap_method( - self.list_occurrences, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_occurrence: self._wrap_method( - self.delete_occurrence, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_occurrence: self._wrap_method( - self.create_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_occurrences: self._wrap_method( - self.batch_create_occurrences, - default_timeout=30.0, - client_info=client_info, - ), - self.update_occurrence: self._wrap_method( - self.update_occurrence, - default_timeout=30.0, - client_info=client_info, - ), - self.get_occurrence_note: self._wrap_method( - self.get_occurrence_note, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.get_note: self._wrap_method( - self.get_note, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.list_notes: self._wrap_method( - self.list_notes, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.delete_note: self._wrap_method( - self.delete_note, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.create_note: self._wrap_method( - self.create_note, - default_timeout=30.0, - client_info=client_info, - ), - self.batch_create_notes: self._wrap_method( - self.batch_create_notes, - default_timeout=30.0, - client_info=client_info, - ), - self.update_note: self._wrap_method( - self.update_note, - default_timeout=30.0, - client_info=client_info, - ), - self.list_note_occurrences: self._wrap_method( - self.list_note_occurrences, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ("GrafeasGrpcAsyncIOTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py deleted file mode 100644 index cadb84765d85..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py +++ /dev/null @@ -1,3034 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, rest_helpers, rest_streaming -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -import google.protobuf -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import json_format -from requests import __version__ as requests_version - -from grafeas.grafeas_v1.types import grafeas - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .rest_base import _BaseGrafeasRestTransport - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class GrafeasRestInterceptor: - """Interceptor for Grafeas. - - 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 GrafeasRestTransport. - - .. code-block:: python - class MyCustomGrafeasInterceptor(GrafeasRestInterceptor): - def pre_batch_create_notes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_notes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_create_occurrences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_occurrences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_occurrence(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_occurrence(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_occurrence_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_occurrence_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_note_occurrences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_note_occurrences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_occurrences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_occurrences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_note(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_note(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_occurrence(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_occurrence(self, response): - logging.log(f"Received response: {response}") - return response - - transport = GrafeasRestTransport(interceptor=MyCustomGrafeasInterceptor()) - client = GrafeasClient(transport=transport) - - - """ - - def pre_batch_create_notes( - self, - request: grafeas.BatchCreateNotesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.BatchCreateNotesRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for batch_create_notes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_batch_create_notes( - self, response: grafeas.BatchCreateNotesResponse - ) -> grafeas.BatchCreateNotesResponse: - """Post-rpc interceptor for batch_create_notes - - DEPRECATED. Please use the `post_batch_create_notes_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_batch_create_notes` interceptor runs - before the `post_batch_create_notes_with_metadata` interceptor. - """ - return response - - def post_batch_create_notes_with_metadata( - self, - response: grafeas.BatchCreateNotesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.BatchCreateNotesResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for batch_create_notes - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_batch_create_notes_with_metadata` - interceptor in new development instead of the `post_batch_create_notes` interceptor. - When both interceptors are used, this `post_batch_create_notes_with_metadata` interceptor runs after the - `post_batch_create_notes` interceptor. The (possibly modified) response returned by - `post_batch_create_notes` will be passed to - `post_batch_create_notes_with_metadata`. - """ - return response, metadata - - def pre_batch_create_occurrences( - self, - request: grafeas.BatchCreateOccurrencesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.BatchCreateOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for batch_create_occurrences - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_batch_create_occurrences( - self, response: grafeas.BatchCreateOccurrencesResponse - ) -> grafeas.BatchCreateOccurrencesResponse: - """Post-rpc interceptor for batch_create_occurrences - - DEPRECATED. Please use the `post_batch_create_occurrences_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_batch_create_occurrences` interceptor runs - before the `post_batch_create_occurrences_with_metadata` interceptor. - """ - return response - - def post_batch_create_occurrences_with_metadata( - self, - response: grafeas.BatchCreateOccurrencesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.BatchCreateOccurrencesResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for batch_create_occurrences - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_batch_create_occurrences_with_metadata` - interceptor in new development instead of the `post_batch_create_occurrences` interceptor. - When both interceptors are used, this `post_batch_create_occurrences_with_metadata` interceptor runs after the - `post_batch_create_occurrences` interceptor. The (possibly modified) response returned by - `post_batch_create_occurrences` will be passed to - `post_batch_create_occurrences_with_metadata`. - """ - return response, metadata - - def pre_create_note( - self, - request: grafeas.CreateNoteRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.CreateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_create_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for create_note - - DEPRECATED. Please use the `post_create_note_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_create_note` interceptor runs - before the `post_create_note_with_metadata` interceptor. - """ - return response - - def post_create_note_with_metadata( - self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_note - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_create_note_with_metadata` - interceptor in new development instead of the `post_create_note` interceptor. - When both interceptors are used, this `post_create_note_with_metadata` interceptor runs after the - `post_create_note` interceptor. The (possibly modified) response returned by - `post_create_note` will be passed to - `post_create_note_with_metadata`. - """ - return response, metadata - - def pre_create_occurrence( - self, - request: grafeas.CreateOccurrenceRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.CreateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for create_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_create_occurrence( - self, response: grafeas.Occurrence - ) -> grafeas.Occurrence: - """Post-rpc interceptor for create_occurrence - - DEPRECATED. Please use the `post_create_occurrence_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_create_occurrence` interceptor runs - before the `post_create_occurrence_with_metadata` interceptor. - """ - return response - - def post_create_occurrence_with_metadata( - self, - response: grafeas.Occurrence, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.Occurrence, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_occurrence - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_create_occurrence_with_metadata` - interceptor in new development instead of the `post_create_occurrence` interceptor. - When both interceptors are used, this `post_create_occurrence_with_metadata` interceptor runs after the - `post_create_occurrence` interceptor. The (possibly modified) response returned by - `post_create_occurrence` will be passed to - `post_create_occurrence_with_metadata`. - """ - return response, metadata - - def pre_delete_note( - self, - request: grafeas.DeleteNoteRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.DeleteNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def pre_delete_occurrence( - self, - request: grafeas.DeleteOccurrenceRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.DeleteOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for delete_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def pre_get_note( - self, - request: grafeas.GetNoteRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.GetNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_get_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for get_note - - DEPRECATED. Please use the `post_get_note_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_get_note` interceptor runs - before the `post_get_note_with_metadata` interceptor. - """ - return response - - def post_get_note_with_metadata( - self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_note - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_get_note_with_metadata` - interceptor in new development instead of the `post_get_note` interceptor. - When both interceptors are used, this `post_get_note_with_metadata` interceptor runs after the - `post_get_note` interceptor. The (possibly modified) response returned by - `post_get_note` will be passed to - `post_get_note_with_metadata`. - """ - return response, metadata - - def pre_get_occurrence( - self, - request: grafeas.GetOccurrenceRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.GetOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_get_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: - """Post-rpc interceptor for get_occurrence - - DEPRECATED. Please use the `post_get_occurrence_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_get_occurrence` interceptor runs - before the `post_get_occurrence_with_metadata` interceptor. - """ - return response - - def post_get_occurrence_with_metadata( - self, - response: grafeas.Occurrence, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.Occurrence, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_occurrence - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_get_occurrence_with_metadata` - interceptor in new development instead of the `post_get_occurrence` interceptor. - When both interceptors are used, this `post_get_occurrence_with_metadata` interceptor runs after the - `post_get_occurrence` interceptor. The (possibly modified) response returned by - `post_get_occurrence` will be passed to - `post_get_occurrence_with_metadata`. - """ - return response, metadata - - def pre_get_occurrence_note( - self, - request: grafeas.GetOccurrenceNoteRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.GetOccurrenceNoteRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for get_occurrence_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_get_occurrence_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for get_occurrence_note - - DEPRECATED. Please use the `post_get_occurrence_note_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_get_occurrence_note` interceptor runs - before the `post_get_occurrence_note_with_metadata` interceptor. - """ - return response - - def post_get_occurrence_note_with_metadata( - self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_occurrence_note - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_get_occurrence_note_with_metadata` - interceptor in new development instead of the `post_get_occurrence_note` interceptor. - When both interceptors are used, this `post_get_occurrence_note_with_metadata` interceptor runs after the - `post_get_occurrence_note` interceptor. The (possibly modified) response returned by - `post_get_occurrence_note` will be passed to - `post_get_occurrence_note_with_metadata`. - """ - return response, metadata - - def pre_list_note_occurrences( - self, - request: grafeas.ListNoteOccurrencesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.ListNoteOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for list_note_occurrences - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_list_note_occurrences( - self, response: grafeas.ListNoteOccurrencesResponse - ) -> grafeas.ListNoteOccurrencesResponse: - """Post-rpc interceptor for list_note_occurrences - - DEPRECATED. Please use the `post_list_note_occurrences_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_list_note_occurrences` interceptor runs - before the `post_list_note_occurrences_with_metadata` interceptor. - """ - return response - - def post_list_note_occurrences_with_metadata( - self, - response: grafeas.ListNoteOccurrencesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.ListNoteOccurrencesResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for list_note_occurrences - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_list_note_occurrences_with_metadata` - interceptor in new development instead of the `post_list_note_occurrences` interceptor. - When both interceptors are used, this `post_list_note_occurrences_with_metadata` interceptor runs after the - `post_list_note_occurrences` interceptor. The (possibly modified) response returned by - `post_list_note_occurrences` will be passed to - `post_list_note_occurrences_with_metadata`. - """ - return response, metadata - - def pre_list_notes( - self, - request: grafeas.ListNotesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.ListNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_notes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_list_notes( - self, response: grafeas.ListNotesResponse - ) -> grafeas.ListNotesResponse: - """Post-rpc interceptor for list_notes - - DEPRECATED. Please use the `post_list_notes_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_list_notes` interceptor runs - before the `post_list_notes_with_metadata` interceptor. - """ - return response - - def post_list_notes_with_metadata( - self, - response: grafeas.ListNotesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.ListNotesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_notes - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_list_notes_with_metadata` - interceptor in new development instead of the `post_list_notes` interceptor. - When both interceptors are used, this `post_list_notes_with_metadata` interceptor runs after the - `post_list_notes` interceptor. The (possibly modified) response returned by - `post_list_notes` will be passed to - `post_list_notes_with_metadata`. - """ - return response, metadata - - def pre_list_occurrences( - self, - request: grafeas.ListOccurrencesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.ListOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_occurrences - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_list_occurrences( - self, response: grafeas.ListOccurrencesResponse - ) -> grafeas.ListOccurrencesResponse: - """Post-rpc interceptor for list_occurrences - - DEPRECATED. Please use the `post_list_occurrences_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_list_occurrences` interceptor runs - before the `post_list_occurrences_with_metadata` interceptor. - """ - return response - - def post_list_occurrences_with_metadata( - self, - response: grafeas.ListOccurrencesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.ListOccurrencesResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for list_occurrences - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_list_occurrences_with_metadata` - interceptor in new development instead of the `post_list_occurrences` interceptor. - When both interceptors are used, this `post_list_occurrences_with_metadata` interceptor runs after the - `post_list_occurrences` interceptor. The (possibly modified) response returned by - `post_list_occurrences` will be passed to - `post_list_occurrences_with_metadata`. - """ - return response, metadata - - def pre_update_note( - self, - request: grafeas.UpdateNoteRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.UpdateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_note - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_update_note(self, response: grafeas.Note) -> grafeas.Note: - """Post-rpc interceptor for update_note - - DEPRECATED. Please use the `post_update_note_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_update_note` interceptor runs - before the `post_update_note_with_metadata` interceptor. - """ - return response - - def post_update_note_with_metadata( - self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_note - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_update_note_with_metadata` - interceptor in new development instead of the `post_update_note` interceptor. - When both interceptors are used, this `post_update_note_with_metadata` interceptor runs after the - `post_update_note` interceptor. The (possibly modified) response returned by - `post_update_note` will be passed to - `post_update_note_with_metadata`. - """ - return response, metadata - - def pre_update_occurrence( - self, - request: grafeas.UpdateOccurrenceRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - grafeas.UpdateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for update_occurrence - - Override in a subclass to manipulate the request or metadata - before they are sent to the Grafeas server. - """ - return request, metadata - - def post_update_occurrence( - self, response: grafeas.Occurrence - ) -> grafeas.Occurrence: - """Post-rpc interceptor for update_occurrence - - DEPRECATED. Please use the `post_update_occurrence_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Grafeas server but before - it is returned to user code. This `post_update_occurrence` interceptor runs - before the `post_update_occurrence_with_metadata` interceptor. - """ - return response - - def post_update_occurrence_with_metadata( - self, - response: grafeas.Occurrence, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[grafeas.Occurrence, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_occurrence - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Grafeas server but before it is returned to user code. - - We recommend only using this `post_update_occurrence_with_metadata` - interceptor in new development instead of the `post_update_occurrence` interceptor. - When both interceptors are used, this `post_update_occurrence_with_metadata` interceptor runs after the - `post_update_occurrence` interceptor. The (possibly modified) response returned by - `post_update_occurrence` will be passed to - `post_update_occurrence_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class GrafeasRestStub: - _session: AuthorizedSession - _host: str - _interceptor: GrafeasRestInterceptor - - -class GrafeasRestTransport(_BaseGrafeasRestTransport): - """REST backend synchronous transport for Grafeas. - - `Grafeas `__ API. - - Retrieves analysis results of Cloud components such as Docker - container images. - - Analysis results are stored as a series of occurrences. An - ``Occurrence`` contains information about a specific analysis - instance on a resource. An occurrence refers to a ``Note``. A note - contains details describing the analysis and is generally stored in - a separate project, called a ``Provider``. Multiple occurrences can - refer to the same note. - - For example, an SSL vulnerability could affect multiple images. In - this case, there would be one note for the vulnerability and an - occurrence for each image with the vulnerability referring to that - note. - - 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 = "", - 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[GrafeasRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: ''). - 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]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - 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 - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience, - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or GrafeasRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BatchCreateNotes( - _BaseGrafeasRestTransport._BaseBatchCreateNotes, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.BatchCreateNotes") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__( - self, - request: grafeas.BatchCreateNotesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateNotesResponse: - r"""Call the batch create notes method over HTTP. - - Args: - request (~.grafeas.BatchCreateNotesRequest): - The request object. Request to create notes in batch. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.BatchCreateNotesResponse: - Response for creating notes in batch. - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_http_options() - ) - - request, metadata = self._interceptor.pre_batch_create_notes( - request, metadata - ) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_transcoded_request( - http_options, request - ) - ) - - body = ( - _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_request_body_json( - transcoded_request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.BatchCreateNotes", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateNotes", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._BatchCreateNotes._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - 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 = grafeas.BatchCreateNotesResponse() - pb_resp = grafeas.BatchCreateNotesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_batch_create_notes(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_create_notes_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.BatchCreateNotesResponse.to_json( - response - ) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.batch_create_notes", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateNotes", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _BatchCreateOccurrences( - _BaseGrafeasRestTransport._BaseBatchCreateOccurrences, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.BatchCreateOccurrences") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__( - self, - request: grafeas.BatchCreateOccurrencesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.BatchCreateOccurrencesResponse: - r"""Call the batch create occurrences method over HTTP. - - Args: - request (~.grafeas.BatchCreateOccurrencesRequest): - The request object. Request to create occurrences in - batch. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.BatchCreateOccurrencesResponse: - Response for creating occurrences in - batch. - - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_http_options() - ) - - request, metadata = self._interceptor.pre_batch_create_occurrences( - request, metadata - ) - transcoded_request = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_transcoded_request( - http_options, request - ) - - body = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_request_body_json( - transcoded_request - ) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.BatchCreateOccurrences", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateOccurrences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._BatchCreateOccurrences._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - 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 = grafeas.BatchCreateOccurrencesResponse() - pb_resp = grafeas.BatchCreateOccurrencesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_batch_create_occurrences(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_create_occurrences_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.BatchCreateOccurrencesResponse.to_json( - response - ) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.batch_create_occurrences", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "BatchCreateOccurrences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateNote(_BaseGrafeasRestTransport._BaseCreateNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.CreateNote") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__( - self, - request: grafeas.CreateNoteRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Call the create note method over HTTP. - - Args: - request (~.grafeas.CreateNoteRequest): - The request object. Request to create a new note. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseCreateNote._get_http_options() - - request, metadata = self._interceptor.pre_create_note(request, metadata) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseCreateNote._get_transcoded_request( - http_options, request - ) - ) - - body = _BaseGrafeasRestTransport._BaseCreateNote._get_request_body_json( - transcoded_request - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseCreateNote._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.CreateNote", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._CreateNote._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - 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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_note(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_note_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Note.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.create_note", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateOccurrence( - _BaseGrafeasRestTransport._BaseCreateOccurrence, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.CreateOccurrence") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__( - self, - request: grafeas.CreateOccurrenceRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Call the create occurrence method over HTTP. - - Args: - request (~.grafeas.CreateOccurrenceRequest): - The request object. Request to create a new occurrence. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseCreateOccurrence._get_http_options() - ) - - request, metadata = self._interceptor.pre_create_occurrence( - request, metadata - ) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseCreateOccurrence._get_transcoded_request( - http_options, request - ) - ) - - body = ( - _BaseGrafeasRestTransport._BaseCreateOccurrence._get_request_body_json( - transcoded_request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseCreateOccurrence._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.CreateOccurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._CreateOccurrence._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - 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 = grafeas.Occurrence() - pb_resp = grafeas.Occurrence.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_occurrence(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_occurrence_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Occurrence.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.create_occurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "CreateOccurrence", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteNote(_BaseGrafeasRestTransport._BaseDeleteNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.DeleteNote") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.DeleteNoteRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): - r"""Call the delete note method over HTTP. - - Args: - request (~.grafeas.DeleteNoteRequest): - The request object. Request to delete a note. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseGrafeasRestTransport._BaseDeleteNote._get_http_options() - - request, metadata = self._interceptor.pre_delete_note(request, metadata) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseDeleteNote._get_transcoded_request( - http_options, request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseDeleteNote._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.DeleteNote", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "DeleteNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._DeleteNote._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteOccurrence( - _BaseGrafeasRestTransport._BaseDeleteOccurrence, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.DeleteOccurrence") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.DeleteOccurrenceRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): - r"""Call the delete occurrence method over HTTP. - - Args: - request (~.grafeas.DeleteOccurrenceRequest): - The request object. Request to delete an occurrence. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_http_options() - ) - - request, metadata = self._interceptor.pre_delete_occurrence( - request, metadata - ) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_transcoded_request( - http_options, request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.DeleteOccurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "DeleteOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._DeleteOccurrence._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetNote(_BaseGrafeasRestTransport._BaseGetNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.GetNote") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.GetNoteRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Call the get note method over HTTP. - - Args: - request (~.grafeas.GetNoteRequest): - The request object. Request to get a note. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseGetNote._get_http_options() - - request, metadata = self._interceptor.pre_get_note(request, metadata) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseGetNote._get_transcoded_request( - http_options, request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseGetNote._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.GetNote", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._GetNote._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # 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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_note(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_note_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Note.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.get_note", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetOccurrence(_BaseGrafeasRestTransport._BaseGetOccurrence, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.GetOccurrence") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.GetOccurrenceRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Call the get occurrence method over HTTP. - - Args: - request (~.grafeas.GetOccurrenceRequest): - The request object. Request to get an occurrence. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseGetOccurrence._get_http_options() - ) - - request, metadata = self._interceptor.pre_get_occurrence(request, metadata) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseGetOccurrence._get_transcoded_request( - http_options, request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseGetOccurrence._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.GetOccurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._GetOccurrence._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # 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 = grafeas.Occurrence() - pb_resp = grafeas.Occurrence.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_occurrence(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_occurrence_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Occurrence.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.get_occurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrence", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetOccurrenceNote( - _BaseGrafeasRestTransport._BaseGetOccurrenceNote, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.GetOccurrenceNote") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.GetOccurrenceNoteRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Call the get occurrence note method over HTTP. - - Args: - request (~.grafeas.GetOccurrenceNoteRequest): - The request object. Request to get the note to which the - specified occurrence is attached. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_http_options() - ) - - request, metadata = self._interceptor.pre_get_occurrence_note( - request, metadata - ) - transcoded_request = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_transcoded_request( - http_options, request - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.GetOccurrenceNote", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrenceNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._GetOccurrenceNote._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # 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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_occurrence_note(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_occurrence_note_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Note.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.get_occurrence_note", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "GetOccurrenceNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListNoteOccurrences( - _BaseGrafeasRestTransport._BaseListNoteOccurrences, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.ListNoteOccurrences") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.ListNoteOccurrencesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.ListNoteOccurrencesResponse: - r"""Call the list note occurrences method over HTTP. - - Args: - request (~.grafeas.ListNoteOccurrencesRequest): - The request object. Request to list occurrences for a - note. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.ListNoteOccurrencesResponse: - Response for listing occurrences for - a note. - - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_http_options() - ) - - request, metadata = self._interceptor.pre_list_note_occurrences( - request, metadata - ) - transcoded_request = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_transcoded_request( - http_options, request - ) - - # Jsonify the query params - query_params = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.ListNoteOccurrences", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNoteOccurrences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._ListNoteOccurrences._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # 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 = grafeas.ListNoteOccurrencesResponse() - pb_resp = grafeas.ListNoteOccurrencesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_note_occurrences(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_note_occurrences_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.ListNoteOccurrencesResponse.to_json( - response - ) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.list_note_occurrences", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNoteOccurrences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListNotes(_BaseGrafeasRestTransport._BaseListNotes, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.ListNotes") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.ListNotesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.ListNotesResponse: - r"""Call the list notes method over HTTP. - - Args: - request (~.grafeas.ListNotesRequest): - The request object. Request to list notes. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.ListNotesResponse: - Response for listing notes. - """ - - http_options = _BaseGrafeasRestTransport._BaseListNotes._get_http_options() - - request, metadata = self._interceptor.pre_list_notes(request, metadata) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseListNotes._get_transcoded_request( - http_options, request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseListNotes._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.ListNotes", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNotes", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._ListNotes._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # 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 = grafeas.ListNotesResponse() - pb_resp = grafeas.ListNotesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_notes(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_notes_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.ListNotesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.list_notes", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListNotes", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListOccurrences( - _BaseGrafeasRestTransport._BaseListOccurrences, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.ListOccurrences") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__( - self, - request: grafeas.ListOccurrencesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.ListOccurrencesResponse: - r"""Call the list occurrences method over HTTP. - - Args: - request (~.grafeas.ListOccurrencesRequest): - The request object. Request to list occurrences. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.ListOccurrencesResponse: - Response for listing occurrences. - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseListOccurrences._get_http_options() - ) - - request, metadata = self._interceptor.pre_list_occurrences( - request, metadata - ) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseListOccurrences._get_transcoded_request( - http_options, request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseListOccurrences._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.ListOccurrences", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListOccurrences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._ListOccurrences._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - - # 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 = grafeas.ListOccurrencesResponse() - pb_resp = grafeas.ListOccurrencesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_occurrences(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_occurrences_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.ListOccurrencesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.list_occurrences", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "ListOccurrences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateNote(_BaseGrafeasRestTransport._BaseUpdateNote, GrafeasRestStub): - def __hash__(self): - return hash("GrafeasRestTransport.UpdateNote") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__( - self, - request: grafeas.UpdateNoteRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Note: - r"""Call the update note method over HTTP. - - Args: - request (~.grafeas.UpdateNoteRequest): - The request object. Request to update a note. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Note: - A type of analysis that can be done - for a resource. - - """ - - http_options = _BaseGrafeasRestTransport._BaseUpdateNote._get_http_options() - - request, metadata = self._interceptor.pre_update_note(request, metadata) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseUpdateNote._get_transcoded_request( - http_options, request - ) - ) - - body = _BaseGrafeasRestTransport._BaseUpdateNote._get_request_body_json( - transcoded_request - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseUpdateNote._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.UpdateNote", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateNote", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._UpdateNote._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - 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 = grafeas.Note() - pb_resp = grafeas.Note.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_note(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_note_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Note.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.update_note", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateNote", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateOccurrence( - _BaseGrafeasRestTransport._BaseUpdateOccurrence, GrafeasRestStub - ): - def __hash__(self): - return hash("GrafeasRestTransport.UpdateOccurrence") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__( - self, - request: grafeas.UpdateOccurrenceRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> grafeas.Occurrence: - r"""Call the update occurrence method over HTTP. - - Args: - request (~.grafeas.UpdateOccurrenceRequest): - The request object. Request to update an occurrence. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.grafeas.Occurrence: - An instance of an analysis type that - has been found on a resource. - - """ - - http_options = ( - _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_http_options() - ) - - request, metadata = self._interceptor.pre_update_occurrence( - request, metadata - ) - transcoded_request = ( - _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_transcoded_request( - http_options, request - ) - ) - - body = ( - _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_request_body_json( - transcoded_request - ) - ) - - # Jsonify the query params - query_params = ( - _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_query_params_json( - transcoded_request - ) - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for grafeas_v1.GrafeasClient.UpdateOccurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateOccurrence", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GrafeasRestTransport._UpdateOccurrence._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - 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 = grafeas.Occurrence() - pb_resp = grafeas.Occurrence.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_occurrence(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_occurrence_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - try: - response_payload = grafeas.Occurrence.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for grafeas_v1.GrafeasClient.update_occurrence", - extra={ - "serviceName": "grafeas.v1.Grafeas", - "rpcName": "UpdateOccurrence", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def batch_create_notes( - self, - ) -> Callable[[grafeas.BatchCreateNotesRequest], grafeas.BatchCreateNotesResponse]: - # 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._BatchCreateNotes(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_create_occurrences( - self, - ) -> Callable[ - [grafeas.BatchCreateOccurrencesRequest], grafeas.BatchCreateOccurrencesResponse - ]: - # 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._BatchCreateOccurrences(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_note(self) -> Callable[[grafeas.CreateNoteRequest], grafeas.Note]: - # 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._CreateNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_occurrence( - self, - ) -> Callable[[grafeas.CreateOccurrenceRequest], grafeas.Occurrence]: - # 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._CreateOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_note(self) -> Callable[[grafeas.DeleteNoteRequest], empty_pb2.Empty]: - # 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._DeleteNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_occurrence( - self, - ) -> Callable[[grafeas.DeleteOccurrenceRequest], empty_pb2.Empty]: - # 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._DeleteOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_note(self) -> Callable[[grafeas.GetNoteRequest], grafeas.Note]: - # 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._GetNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_occurrence( - self, - ) -> Callable[[grafeas.GetOccurrenceRequest], grafeas.Occurrence]: - # 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._GetOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_occurrence_note( - self, - ) -> Callable[[grafeas.GetOccurrenceNoteRequest], grafeas.Note]: - # 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._GetOccurrenceNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_note_occurrences( - self, - ) -> Callable[ - [grafeas.ListNoteOccurrencesRequest], grafeas.ListNoteOccurrencesResponse - ]: - # 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._ListNoteOccurrences(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notes( - self, - ) -> Callable[[grafeas.ListNotesRequest], grafeas.ListNotesResponse]: - # 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._ListNotes(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_occurrences( - self, - ) -> Callable[[grafeas.ListOccurrencesRequest], grafeas.ListOccurrencesResponse]: - # 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._ListOccurrences(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_note(self) -> Callable[[grafeas.UpdateNoteRequest], grafeas.Note]: - # 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._UpdateNote(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_occurrence( - self, - ) -> Callable[[grafeas.UpdateOccurrenceRequest], grafeas.Occurrence]: - # 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._UpdateOccurrence(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__ = ("GrafeasRestTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py deleted file mode 100644 index dd852b1d486b..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py +++ /dev/null @@ -1,874 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 json # type: ignore -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1, path_template -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import json_format - -from grafeas.grafeas_v1.types import grafeas - -from .base import DEFAULT_CLIENT_INFO, GrafeasTransport - - -class _BaseGrafeasRestTransport(GrafeasTransport): - """Base REST backend transport for Grafeas. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - 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 = "containeranalysis.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'containeranalysis.googleapis.com'). - credentials (Optional[Any]): 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. - 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 - 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, - ) - - class _BaseBatchCreateNotes: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*}/notes:batchCreate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/notes:batchCreate", - "body": "*", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.BatchCreateNotesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseBatchCreateOccurrences: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*}/occurrences:batchCreate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/occurrences:batchCreate", - "body": "*", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.BatchCreateOccurrencesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateNote: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "noteId": "", - } - - @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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*}/notes", - "body": "note", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/notes", - "body": "note", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.CreateNoteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseCreateNote._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateOccurrence: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*}/occurrences", - "body": "occurrence", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/occurrences", - "body": "occurrence", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.CreateOccurrenceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseCreateOccurrence._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteNote: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/notes/*}", - }, - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/notes/*}", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.DeleteNoteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseDeleteNote._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteOccurrence: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/occurrences/*}", - }, - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/occurrences/*}", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.DeleteOccurrenceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetNote: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/notes/*}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/notes/*}", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.GetNoteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseGetNote._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOccurrence: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/occurrences/*}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/occurrences/*}", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.GetOccurrenceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseGetOccurrence._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOccurrenceNote: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/occurrences/*}/notes", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/occurrences/*}/notes", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.GetOccurrenceNoteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListNoteOccurrences: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/notes/*}/occurrences", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/notes/*}/occurrences", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.ListNoteOccurrencesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListNotes: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*}/notes", - }, - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/notes", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.ListNotesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseListNotes._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListOccurrences: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*}/occurrences", - }, - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/occurrences", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.ListOccurrencesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseListOccurrences._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateNote: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{name=projects/*/notes/*}", - "body": "note", - }, - { - "method": "patch", - "uri": "/v1/{name=projects/*/locations/*/notes/*}", - "body": "note", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.UpdateNoteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseUpdateNote._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateOccurrence: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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 - } - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{name=projects/*/occurrences/*}", - "body": "occurrence", - }, - { - "method": "patch", - "uri": "/v1/{name=projects/*/locations/*/occurrences/*}", - "body": "occurrence", - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = grafeas.UpdateOccurrenceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_unset_required_fields( - query_params - ) - ) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__ = ("_BaseGrafeasRestTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/__init__.py b/packages/grafeas/grafeas/grafeas_v1/types/__init__.py deleted file mode 100644 index 66635ba28b86..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/__init__.py +++ /dev/null @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 .attestation import AttestationNote, AttestationOccurrence, Jwt -from .build import BuildNote, BuildOccurrence -from .common import ( - BaseImage, - Digest, - Envelope, - EnvelopeSignature, - FileLocation, - LayerDetails, - License, - NoteKind, - RelatedUrl, - Signature, -) -from .compliance import ( - ComplianceNote, - ComplianceOccurrence, - ComplianceVersion, - NonCompliantFile, -) -from .cvss import CVSS, CVSSv3, CVSSVersion -from .deployment import DeploymentNote, DeploymentOccurrence -from .discovery import DiscoveryNote, DiscoveryOccurrence -from .dsse_attestation import DSSEAttestationNote, DSSEAttestationOccurrence -from .grafeas import ( - BatchCreateNotesRequest, - BatchCreateNotesResponse, - BatchCreateOccurrencesRequest, - BatchCreateOccurrencesResponse, - CreateNoteRequest, - CreateOccurrenceRequest, - DeleteNoteRequest, - DeleteOccurrenceRequest, - GetNoteRequest, - GetOccurrenceNoteRequest, - GetOccurrenceRequest, - ListNoteOccurrencesRequest, - ListNoteOccurrencesResponse, - ListNotesRequest, - ListNotesResponse, - ListOccurrencesRequest, - ListOccurrencesResponse, - Note, - Occurrence, - UpdateNoteRequest, - UpdateOccurrenceRequest, -) -from .image import Fingerprint, ImageNote, ImageOccurrence, Layer -from .intoto_provenance import ( - BuilderConfig, - Completeness, - InTotoProvenance, - Metadata, - Recipe, -) -from .intoto_statement import InTotoSlsaProvenanceV1, InTotoStatement, Subject -from .package import ( - Architecture, - Distribution, - Location, - PackageNote, - PackageOccurrence, - Version, -) -from .provenance import ( - AliasContext, - Artifact, - BuildProvenance, - CloudRepoSourceContext, - Command, - FileHashes, - GerritSourceContext, - GitSourceContext, - Hash, - ProjectRepoId, - RepoId, - Source, - SourceContext, -) -from .sbom import ( - SbomReferenceIntotoPayload, - SbomReferenceIntotoPredicate, - SBOMReferenceNote, - SBOMReferenceOccurrence, -) -from .secret import ( - SecretKind, - SecretLocation, - SecretNote, - SecretOccurrence, - SecretStatus, -) -from .severity import Severity -from .slsa_provenance import SlsaProvenance -from .slsa_provenance_zero_two import SlsaProvenanceZeroTwo -from .upgrade import UpgradeDistribution, UpgradeNote, UpgradeOccurrence, WindowsUpdate -from .vex import VulnerabilityAssessmentNote -from .vulnerability import VulnerabilityNote, VulnerabilityOccurrence - -__all__ = ( - "AttestationNote", - "AttestationOccurrence", - "Jwt", - "BuildNote", - "BuildOccurrence", - "BaseImage", - "Digest", - "Envelope", - "EnvelopeSignature", - "FileLocation", - "LayerDetails", - "License", - "RelatedUrl", - "Signature", - "NoteKind", - "ComplianceNote", - "ComplianceOccurrence", - "ComplianceVersion", - "NonCompliantFile", - "CVSS", - "CVSSv3", - "CVSSVersion", - "DeploymentNote", - "DeploymentOccurrence", - "DiscoveryNote", - "DiscoveryOccurrence", - "DSSEAttestationNote", - "DSSEAttestationOccurrence", - "BatchCreateNotesRequest", - "BatchCreateNotesResponse", - "BatchCreateOccurrencesRequest", - "BatchCreateOccurrencesResponse", - "CreateNoteRequest", - "CreateOccurrenceRequest", - "DeleteNoteRequest", - "DeleteOccurrenceRequest", - "GetNoteRequest", - "GetOccurrenceNoteRequest", - "GetOccurrenceRequest", - "ListNoteOccurrencesRequest", - "ListNoteOccurrencesResponse", - "ListNotesRequest", - "ListNotesResponse", - "ListOccurrencesRequest", - "ListOccurrencesResponse", - "Note", - "Occurrence", - "UpdateNoteRequest", - "UpdateOccurrenceRequest", - "Fingerprint", - "ImageNote", - "ImageOccurrence", - "Layer", - "BuilderConfig", - "Completeness", - "InTotoProvenance", - "Metadata", - "Recipe", - "InTotoSlsaProvenanceV1", - "InTotoStatement", - "Subject", - "Distribution", - "Location", - "PackageNote", - "PackageOccurrence", - "Version", - "Architecture", - "AliasContext", - "Artifact", - "BuildProvenance", - "CloudRepoSourceContext", - "Command", - "FileHashes", - "GerritSourceContext", - "GitSourceContext", - "Hash", - "ProjectRepoId", - "RepoId", - "Source", - "SourceContext", - "SbomReferenceIntotoPayload", - "SbomReferenceIntotoPredicate", - "SBOMReferenceNote", - "SBOMReferenceOccurrence", - "SecretLocation", - "SecretNote", - "SecretOccurrence", - "SecretStatus", - "SecretKind", - "Severity", - "SlsaProvenance", - "SlsaProvenanceZeroTwo", - "UpgradeDistribution", - "UpgradeNote", - "UpgradeOccurrence", - "WindowsUpdate", - "VulnerabilityAssessmentNote", - "VulnerabilityNote", - "VulnerabilityOccurrence", -) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/attestation.py b/packages/grafeas/grafeas/grafeas_v1/types/attestation.py deleted file mode 100644 index 5d0229daac9c..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/attestation.py +++ /dev/null @@ -1,147 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import common - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "AttestationNote", - "Jwt", - "AttestationOccurrence", - }, -) - - -class AttestationNote(proto.Message): - r"""Note kind that represents a logical attestation "role" or - "authority". For example, an organization might have one - ``Authority`` for "QA" and one for "build". This note is intended to - act strictly as a grouping mechanism for the attached occurrences - (Attestations). This grouping mechanism also provides a security - boundary, since IAM ACLs gate the ability for a principle to attach - an occurrence to a given note. It also provides a single point of - lookup to find all attached attestation occurrences, even if they - don't all live in the same project. - - Attributes: - hint (grafeas.grafeas_v1.types.AttestationNote.Hint): - Hint hints at the purpose of the attestation - authority. - """ - - class Hint(proto.Message): - r"""This submessage provides human-readable hints about the - purpose of the authority. Because the name of a note acts as its - resource reference, it is important to disambiguate the - canonical name of the Note (which might be a UUID for security - purposes) from "readable" names more suitable for debug output. - Note that these hints should not be used to look up authorities - in security sensitive contexts, such as when looking up - attestations to verify. - - Attributes: - human_readable_name (str): - Required. The human readable name of this - attestation authority, for example "qa". - """ - - human_readable_name: str = proto.Field( - proto.STRING, - number=1, - ) - - hint: Hint = proto.Field( - proto.MESSAGE, - number=1, - message=Hint, - ) - - -class Jwt(proto.Message): - r""" - - Attributes: - compact_jwt (str): - The compact encoding of a JWS, which is - always three base64 encoded strings joined by - periods. For details, see: - - https://tools.ietf.org/html/rfc7515.html#section-3.1 - """ - - compact_jwt: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AttestationOccurrence(proto.Message): - r"""Occurrence that represents a single "attestation". The - authenticity of an attestation can be verified using the - attached signature. If the verifier trusts the public key of the - signer, then verifying the signature is sufficient to establish - trust. In this circumstance, the authority to which this - attestation is attached is primarily useful for lookup (how to - find this attestation if you already know the authority and - artifact to be verified) and intent (for which authority this - attestation was intended to sign. - - Attributes: - serialized_payload (bytes): - Required. The serialized payload that is verified by one or - more ``signatures``. - signatures (MutableSequence[grafeas.grafeas_v1.types.Signature]): - One or more signatures over ``serialized_payload``. Verifier - implementations should consider this attestation message - verified if at least one ``signature`` verifies - ``serialized_payload``. See ``Signature`` in common.proto - for more details on signature structure and verification. - jwts (MutableSequence[grafeas.grafeas_v1.types.Jwt]): - One or more JWTs encoding a self-contained attestation. Each - JWT encodes the payload that it verifies within the JWT - itself. Verifier implementation SHOULD ignore the - ``serialized_payload`` field when verifying these JWTs. If - only JWTs are present on this AttestationOccurrence, then - the ``serialized_payload`` SHOULD be left empty. Each JWT - SHOULD encode a claim specific to the ``resource_uri`` of - this Occurrence, but this is not validated by Grafeas - metadata API implementations. The JWT itself is opaque to - Grafeas. - """ - - serialized_payload: bytes = proto.Field( - proto.BYTES, - number=1, - ) - signatures: MutableSequence[common.Signature] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Signature, - ) - jwts: MutableSequence["Jwt"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Jwt", - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/build.py b/packages/grafeas/grafeas/grafeas_v1/types/build.py deleted file mode 100644 index 837f08b2249e..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/build.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import intoto_provenance as g_intoto_provenance -from grafeas.grafeas_v1.types import intoto_statement as g_intoto_statement -from grafeas.grafeas_v1.types import provenance as g_provenance - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "BuildNote", - "BuildOccurrence", - }, -) - - -class BuildNote(proto.Message): - r"""Note holding the version of the provider's builder and the - signature of the provenance message in the build details - occurrence. - - Attributes: - builder_version (str): - Required. Immutable. Version of the builder - which produced this build. - """ - - builder_version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class BuildOccurrence(proto.Message): - r"""Details of a build occurrence. - - Attributes: - provenance (grafeas.grafeas_v1.types.BuildProvenance): - The actual provenance for the build. - provenance_bytes (str): - Serialized JSON representation of the provenance, used in - generating the build signature in the corresponding build - note. After verifying the signature, ``provenance_bytes`` - can be unmarshalled and compared to the provenance to - confirm that it is unchanged. A base64-encoded string - representation of the provenance bytes is used for the - signature in order to interoperate with openssl which - expects this format for signature verification. - - The serialized form is captured both to avoid ambiguity in - how the provenance is marshalled to json as well to prevent - incompatibilities with future changes. - intoto_provenance (grafeas.grafeas_v1.types.InTotoProvenance): - Deprecated. See InTotoStatement for the - replacement. In-toto Provenance representation - as defined in spec. - intoto_statement (grafeas.grafeas_v1.types.InTotoStatement): - In-toto Statement representation as defined in spec. The - intoto_statement can contain any type of provenance. The - serialized payload of the statement can be stored and signed - in the Occurrence's envelope. - in_toto_slsa_provenance_v1 (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1): - In-Toto Slsa Provenance V1 represents a slsa - provenance meeting the slsa spec, wrapped in an - in-toto statement. This allows for direct - jsonification of a to-spec in-toto slsa - statement with a to-spec slsa provenance. - """ - - provenance: g_provenance.BuildProvenance = proto.Field( - proto.MESSAGE, - number=1, - message=g_provenance.BuildProvenance, - ) - provenance_bytes: str = proto.Field( - proto.STRING, - number=2, - ) - intoto_provenance: g_intoto_provenance.InTotoProvenance = proto.Field( - proto.MESSAGE, - number=3, - message=g_intoto_provenance.InTotoProvenance, - ) - intoto_statement: g_intoto_statement.InTotoStatement = proto.Field( - proto.MESSAGE, - number=4, - message=g_intoto_statement.InTotoStatement, - ) - in_toto_slsa_provenance_v1: g_intoto_statement.InTotoSlsaProvenanceV1 = proto.Field( - proto.MESSAGE, - number=5, - message=g_intoto_statement.InTotoSlsaProvenanceV1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/common.py b/packages/grafeas/grafeas/grafeas_v1/types/common.py deleted file mode 100644 index 45d9b9e23c13..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/common.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "NoteKind", - "RelatedUrl", - "Signature", - "Envelope", - "EnvelopeSignature", - "FileLocation", - "BaseImage", - "LayerDetails", - "License", - "Digest", - }, -) - - -class NoteKind(proto.Enum): - r"""Kind represents the kinds of notes supported. - - Values: - NOTE_KIND_UNSPECIFIED (0): - Default value. This value is unused. - VULNERABILITY (1): - The note and occurrence represent a package - vulnerability. - BUILD (2): - The note and occurrence assert build - provenance. - IMAGE (3): - This represents an image basis relationship. - PACKAGE (4): - This represents a package installed via a - package manager. - DEPLOYMENT (5): - The note and occurrence track deployment - events. - DISCOVERY (6): - The note and occurrence track the initial - discovery status of a resource. - ATTESTATION (7): - This represents a logical "role" that can - attest to artifacts. - UPGRADE (8): - This represents an available package upgrade. - COMPLIANCE (9): - This represents a Compliance Note - DSSE_ATTESTATION (10): - This represents a DSSE attestation Note - VULNERABILITY_ASSESSMENT (11): - This represents a Vulnerability Assessment. - SBOM_REFERENCE (12): - This represents an SBOM Reference. - SECRET (13): - This represents a secret. - """ - NOTE_KIND_UNSPECIFIED = 0 - VULNERABILITY = 1 - BUILD = 2 - IMAGE = 3 - PACKAGE = 4 - DEPLOYMENT = 5 - DISCOVERY = 6 - ATTESTATION = 7 - UPGRADE = 8 - COMPLIANCE = 9 - DSSE_ATTESTATION = 10 - VULNERABILITY_ASSESSMENT = 11 - SBOM_REFERENCE = 12 - SECRET = 13 - - -class RelatedUrl(proto.Message): - r"""Metadata for any related URL information. - - Attributes: - url (str): - Specific URL associated with the resource. - label (str): - Label to describe usage of the URL. - """ - - url: str = proto.Field( - proto.STRING, - number=1, - ) - label: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Signature(proto.Message): - r"""Verifiers (e.g. Kritis implementations) MUST verify signatures with - respect to the trust anchors defined in policy (e.g. a Kritis - policy). Typically this means that the verifier has been configured - with a map from ``public_key_id`` to public key material (and any - required parameters, e.g. signing algorithm). - - In particular, verification implementations MUST NOT treat the - signature ``public_key_id`` as anything more than a key lookup hint. - The ``public_key_id`` DOES NOT validate or authenticate a public - key; it only provides a mechanism for quickly selecting a public key - ALREADY CONFIGURED on the verifier through a trusted channel. - Verification implementations MUST reject signatures in any of the - following circumstances: - - - The ``public_key_id`` is not recognized by the verifier. - - The public key that ``public_key_id`` refers to does not verify - the signature with respect to the payload. - - The ``signature`` contents SHOULD NOT be "attached" (where the - payload is included with the serialized ``signature`` bytes). - Verifiers MUST ignore any "attached" payload and only verify - signatures with respect to explicitly provided payload (e.g. a - ``payload`` field on the proto message that holds this Signature, or - the canonical serialization of the proto message that holds this - signature). - - Attributes: - signature (bytes): - The content of the signature, an opaque - bytestring. The payload that this signature - verifies MUST be unambiguously provided with the - Signature during verification. A wrapper message - might provide the payload explicitly. - Alternatively, a message might have a canonical - serialization that can always be unambiguously - computed to derive the payload. - public_key_id (str): - The identifier for the public key that verifies this - signature. - - - The ``public_key_id`` is required. - - The ``public_key_id`` SHOULD be an RFC3986 conformant URI. - - When possible, the ``public_key_id`` SHOULD be an - immutable reference, such as a cryptographic digest. - - Examples of valid ``public_key_id``\ s: - - OpenPGP V4 public key fingerprint: - - - "openpgp4fpr:74FAF3B861BDA0870C7B6DEF607E48D2A663AEEA" See - https://www.iana.org/assignments/uri-schemes/prov/openpgp4fpr - for more details on this scheme. - - RFC6920 digest-named SubjectPublicKeyInfo (digest of the DER - serialization): - - - "ni:///sha-256;cD9o9Cq6LG3jD0iKXqEi_vdjJGecm_iXkbqVoScViaU" - - "nih:///sha-256;703f68f42aba2c6de30f488a5ea122fef76324679c9bf89791ba95a1271589a5". - """ - - signature: bytes = proto.Field( - proto.BYTES, - number=1, - ) - public_key_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Envelope(proto.Message): - r"""MUST match - https://github.com/secure-systems-lab/dsse/blob/master/envelope.proto. - An authenticated message of arbitrary type. - - Attributes: - payload (bytes): - - payload_type (str): - - signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): - - """ - - payload: bytes = proto.Field( - proto.BYTES, - number=1, - ) - payload_type: str = proto.Field( - proto.STRING, - number=2, - ) - signatures: MutableSequence["EnvelopeSignature"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="EnvelopeSignature", - ) - - -class EnvelopeSignature(proto.Message): - r""" - - Attributes: - sig (bytes): - - keyid (str): - - """ - - sig: bytes = proto.Field( - proto.BYTES, - number=1, - ) - keyid: str = proto.Field( - proto.STRING, - number=2, - ) - - -class FileLocation(proto.Message): - r"""Indicates the location at which a package was found. - - Attributes: - file_path (str): - For jars that are contained inside .war - files, this filepath can indicate the path to - war file combined with the path to jar file. - layer_details (grafeas.grafeas_v1.types.LayerDetails): - Each package found in a file should have its - own layer metadata (that is, information from - the origin layer of the package). - """ - - file_path: str = proto.Field( - proto.STRING, - number=1, - ) - layer_details: "LayerDetails" = proto.Field( - proto.MESSAGE, - number=2, - message="LayerDetails", - ) - - -class BaseImage(proto.Message): - r"""BaseImage describes a base image of a container image. - - Attributes: - name (str): - The name of the base image. - repository (str): - The repository name in which the base image - is from. - layer_count (int): - The number of layers that the base image is - composed of. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - repository: str = proto.Field( - proto.STRING, - number=2, - ) - layer_count: int = proto.Field( - proto.INT32, - number=3, - ) - - -class LayerDetails(proto.Message): - r"""Details about the layer a package was found in. - - Attributes: - index (int): - The index of the layer in the container - image. - diff_id (str): - The diff ID (typically a sha256 hash) of the - layer in the container image. - chain_id (str): - The layer chain ID (sha256 hash) of the layer - in the container image. - https://github.com/opencontainers/image-spec/blob/main/config.md#layer-chainid - command (str): - The layer build command that was used to - build the layer. This may not be found in all - layers depending on how the container image is - built. - base_images (MutableSequence[grafeas.grafeas_v1.types.BaseImage]): - The base images the layer is found within. - """ - - index: int = proto.Field( - proto.INT32, - number=1, - ) - diff_id: str = proto.Field( - proto.STRING, - number=2, - ) - chain_id: str = proto.Field( - proto.STRING, - number=5, - ) - command: str = proto.Field( - proto.STRING, - number=3, - ) - base_images: MutableSequence["BaseImage"] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message="BaseImage", - ) - - -class License(proto.Message): - r"""License information. - - Attributes: - expression (str): - Often a single license can be used to - represent the licensing terms. Sometimes it is - necessary to include a choice of one or more - licenses or some combination of license - identifiers. - Examples: "LGPL-2.1-only OR MIT", "LGPL-2.1-only - AND MIT", "GPL-2.0-or-later WITH - Bison-exception-2.2". - comments (str): - Comments - """ - - expression: str = proto.Field( - proto.STRING, - number=1, - ) - comments: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Digest(proto.Message): - r"""Digest information. - - Attributes: - algo (str): - ``SHA1``, ``SHA512`` etc. - digest_bytes (bytes): - Value of the digest. - """ - - algo: str = proto.Field( - proto.STRING, - number=1, - ) - digest_bytes: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/compliance.py b/packages/grafeas/grafeas/grafeas_v1/types/compliance.py deleted file mode 100644 index 5cd9cb5fd59f..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/compliance.py +++ /dev/null @@ -1,214 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import severity as g_severity - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "ComplianceNote", - "ComplianceVersion", - "ComplianceOccurrence", - "NonCompliantFile", - }, -) - - -class ComplianceNote(proto.Message): - r""" - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - title (str): - The title that identifies this compliance - check. - description (str): - A description about this compliance check. - version (MutableSequence[grafeas.grafeas_v1.types.ComplianceVersion]): - The OS and config versions the benchmark - applies to. - rationale (str): - A rationale for the existence of this - compliance check. - remediation (str): - A description of remediation steps if the - compliance check fails. - cis_benchmark (grafeas.grafeas_v1.types.ComplianceNote.CisBenchmark): - - This field is a member of `oneof`_ ``compliance_type``. - scan_instructions (bytes): - Serialized scan instructions with a - predefined format. - impact (str): - - This field is a member of `oneof`_ ``potential_impact``. - """ - - class CisBenchmark(proto.Message): - r"""A compliance check that is a CIS benchmark. - - Attributes: - profile_level (int): - - severity (grafeas.grafeas_v1.types.Severity): - - """ - - profile_level: int = proto.Field( - proto.INT32, - number=1, - ) - severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=2, - enum=g_severity.Severity, - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - version: MutableSequence["ComplianceVersion"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="ComplianceVersion", - ) - rationale: str = proto.Field( - proto.STRING, - number=4, - ) - remediation: str = proto.Field( - proto.STRING, - number=5, - ) - cis_benchmark: CisBenchmark = proto.Field( - proto.MESSAGE, - number=6, - oneof="compliance_type", - message=CisBenchmark, - ) - scan_instructions: bytes = proto.Field( - proto.BYTES, - number=7, - ) - impact: str = proto.Field( - proto.STRING, - number=8, - oneof="potential_impact", - ) - - -class ComplianceVersion(proto.Message): - r"""Describes the CIS benchmark version that is applicable to a - given OS and os version. - - Attributes: - cpe_uri (str): - The CPE URI - (https://cpe.mitre.org/specification/) this - benchmark is applicable to. - benchmark_document (str): - The name of the document that defines this - benchmark, e.g. "CIS Container-Optimized OS". - version (str): - The version of the benchmark. This is set to - the version of the OS-specific CIS document the - benchmark is defined in. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - benchmark_document: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ComplianceOccurrence(proto.Message): - r"""An indication that the compliance checks in the associated - ComplianceNote were not satisfied for particular resources or a - specified reason. - - Attributes: - non_compliant_files (MutableSequence[grafeas.grafeas_v1.types.NonCompliantFile]): - - non_compliance_reason (str): - - version (grafeas.grafeas_v1.types.ComplianceVersion): - The OS and config version the benchmark was - run on. - """ - - non_compliant_files: MutableSequence["NonCompliantFile"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="NonCompliantFile", - ) - non_compliance_reason: str = proto.Field( - proto.STRING, - number=3, - ) - version: "ComplianceVersion" = proto.Field( - proto.MESSAGE, - number=4, - message="ComplianceVersion", - ) - - -class NonCompliantFile(proto.Message): - r"""Details about files that caused a compliance check to fail. - - Attributes: - path (str): - Empty if ``display_command`` is set. - display_command (str): - Command to display the non-compliant files. - reason (str): - Explains why a file is non compliant for a - CIS check. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - display_command: str = proto.Field( - proto.STRING, - number=2, - ) - reason: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/cvss.py b/packages/grafeas/grafeas/grafeas_v1/types/cvss.py deleted file mode 100644 index 68c78c55c516..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/cvss.py +++ /dev/null @@ -1,465 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "CVSSVersion", - "CVSSv3", - "CVSS", - }, -) - - -class CVSSVersion(proto.Enum): - r"""CVSS Version. - - Values: - CVSS_VERSION_UNSPECIFIED (0): - No description available. - CVSS_VERSION_2 (1): - No description available. - CVSS_VERSION_3 (2): - No description available. - """ - CVSS_VERSION_UNSPECIFIED = 0 - CVSS_VERSION_2 = 1 - CVSS_VERSION_3 = 2 - - -class CVSSv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - For details, see - https://www.first.org/cvss/specification-document - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - exploitability_score (float): - - impact_score (float): - - attack_vector (grafeas.grafeas_v1.types.CVSSv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. - attack_complexity (grafeas.grafeas_v1.types.CVSSv3.AttackComplexity): - - privileges_required (grafeas.grafeas_v1.types.CVSSv3.PrivilegesRequired): - - user_interaction (grafeas.grafeas_v1.types.CVSSv3.UserInteraction): - - scope (grafeas.grafeas_v1.types.CVSSv3.Scope): - - confidentiality_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - integrity_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - availability_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): - - """ - - class AttackVector(proto.Enum): - r""" - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - No description available. - ATTACK_VECTOR_NETWORK (1): - No description available. - ATTACK_VECTOR_ADJACENT (2): - No description available. - ATTACK_VECTOR_LOCAL (3): - No description available. - ATTACK_VECTOR_PHYSICAL (4): - No description available. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r""" - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - No description available. - ATTACK_COMPLEXITY_LOW (1): - No description available. - ATTACK_COMPLEXITY_HIGH (2): - No description available. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r""" - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - No description available. - PRIVILEGES_REQUIRED_NONE (1): - No description available. - PRIVILEGES_REQUIRED_LOW (2): - No description available. - PRIVILEGES_REQUIRED_HIGH (3): - No description available. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r""" - - Values: - USER_INTERACTION_UNSPECIFIED (0): - No description available. - USER_INTERACTION_NONE (1): - No description available. - USER_INTERACTION_REQUIRED (2): - No description available. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r""" - - Values: - SCOPE_UNSPECIFIED (0): - No description available. - SCOPE_UNCHANGED (1): - No description available. - SCOPE_CHANGED (2): - No description available. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r""" - - Values: - IMPACT_UNSPECIFIED (0): - No description available. - IMPACT_HIGH (1): - No description available. - IMPACT_LOW (2): - No description available. - IMPACT_NONE (3): - No description available. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - exploitability_score: float = proto.Field( - proto.FLOAT, - number=2, - ) - impact_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=5, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=6, - enum=AttackComplexity, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -class CVSS(proto.Message): - r"""Common Vulnerability Scoring System. - For details, see - https://www.first.org/cvss/specification-document This is a - message we will try to use for storing various versions of CVSS - rather than making a separate proto for storing a specific - version. - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - exploitability_score (float): - - impact_score (float): - - attack_vector (grafeas.grafeas_v1.types.CVSS.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. - attack_complexity (grafeas.grafeas_v1.types.CVSS.AttackComplexity): - - authentication (grafeas.grafeas_v1.types.CVSS.Authentication): - - privileges_required (grafeas.grafeas_v1.types.CVSS.PrivilegesRequired): - - user_interaction (grafeas.grafeas_v1.types.CVSS.UserInteraction): - - scope (grafeas.grafeas_v1.types.CVSS.Scope): - - confidentiality_impact (grafeas.grafeas_v1.types.CVSS.Impact): - - integrity_impact (grafeas.grafeas_v1.types.CVSS.Impact): - - availability_impact (grafeas.grafeas_v1.types.CVSS.Impact): - - """ - - class AttackVector(proto.Enum): - r""" - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - No description available. - ATTACK_VECTOR_NETWORK (1): - No description available. - ATTACK_VECTOR_ADJACENT (2): - No description available. - ATTACK_VECTOR_LOCAL (3): - No description available. - ATTACK_VECTOR_PHYSICAL (4): - No description available. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r""" - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - No description available. - ATTACK_COMPLEXITY_LOW (1): - No description available. - ATTACK_COMPLEXITY_HIGH (2): - No description available. - ATTACK_COMPLEXITY_MEDIUM (3): - No description available. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - ATTACK_COMPLEXITY_MEDIUM = 3 - - class Authentication(proto.Enum): - r""" - - Values: - AUTHENTICATION_UNSPECIFIED (0): - No description available. - AUTHENTICATION_MULTIPLE (1): - No description available. - AUTHENTICATION_SINGLE (2): - No description available. - AUTHENTICATION_NONE (3): - No description available. - """ - AUTHENTICATION_UNSPECIFIED = 0 - AUTHENTICATION_MULTIPLE = 1 - AUTHENTICATION_SINGLE = 2 - AUTHENTICATION_NONE = 3 - - class PrivilegesRequired(proto.Enum): - r""" - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - No description available. - PRIVILEGES_REQUIRED_NONE (1): - No description available. - PRIVILEGES_REQUIRED_LOW (2): - No description available. - PRIVILEGES_REQUIRED_HIGH (3): - No description available. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r""" - - Values: - USER_INTERACTION_UNSPECIFIED (0): - No description available. - USER_INTERACTION_NONE (1): - No description available. - USER_INTERACTION_REQUIRED (2): - No description available. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r""" - - Values: - SCOPE_UNSPECIFIED (0): - No description available. - SCOPE_UNCHANGED (1): - No description available. - SCOPE_CHANGED (2): - No description available. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r""" - - Values: - IMPACT_UNSPECIFIED (0): - No description available. - IMPACT_HIGH (1): - No description available. - IMPACT_LOW (2): - No description available. - IMPACT_NONE (3): - No description available. - IMPACT_PARTIAL (4): - No description available. - IMPACT_COMPLETE (5): - No description available. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - IMPACT_PARTIAL = 4 - IMPACT_COMPLETE = 5 - - base_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - exploitability_score: float = proto.Field( - proto.FLOAT, - number=2, - ) - impact_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=4, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=5, - enum=AttackComplexity, - ) - authentication: Authentication = proto.Field( - proto.ENUM, - number=6, - enum=Authentication, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/deployment.py b/packages/grafeas/grafeas/grafeas_v1/types/deployment.py deleted file mode 100644 index 9d41a4aa7764..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/deployment.py +++ /dev/null @@ -1,124 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "DeploymentNote", - "DeploymentOccurrence", - }, -) - - -class DeploymentNote(proto.Message): - r"""An artifact that can be deployed in some runtime. - - Attributes: - resource_uri (MutableSequence[str]): - Required. Resource URI for the artifact being - deployed. - """ - - resource_uri: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class DeploymentOccurrence(proto.Message): - r"""The period during which some deployable was active in a - runtime. - - Attributes: - user_email (str): - Identity of the user that triggered this - deployment. - deploy_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Beginning of the lifetime of this - deployment. - undeploy_time (google.protobuf.timestamp_pb2.Timestamp): - End of the lifetime of this deployment. - config (str): - Configuration used to create this deployment. - address (str): - Address of the runtime element hosting this - deployment. - resource_uri (MutableSequence[str]): - Output only. Resource URI for the artifact - being deployed taken from the deployable field - with the same name. - platform (grafeas.grafeas_v1.types.DeploymentOccurrence.Platform): - Platform hosting this deployment. - """ - - class Platform(proto.Enum): - r"""Types of platforms. - - Values: - PLATFORM_UNSPECIFIED (0): - Unknown. - GKE (1): - Google Container Engine. - FLEX (2): - Google App Engine: Flexible Environment. - CUSTOM (3): - Custom user-defined platform. - """ - PLATFORM_UNSPECIFIED = 0 - GKE = 1 - FLEX = 2 - CUSTOM = 3 - - user_email: str = proto.Field( - proto.STRING, - number=1, - ) - deploy_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - undeploy_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - config: str = proto.Field( - proto.STRING, - number=4, - ) - address: str = proto.Field( - proto.STRING, - number=5, - ) - resource_uri: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - platform: Platform = proto.Field( - proto.ENUM, - number=7, - enum=Platform, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/discovery.py b/packages/grafeas/grafeas/grafeas_v1/types/discovery.py deleted file mode 100644 index 9a6b9d17c47e..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/discovery.py +++ /dev/null @@ -1,283 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import common - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "DiscoveryNote", - "DiscoveryOccurrence", - }, -) - - -class DiscoveryNote(proto.Message): - r"""A note that indicates a type of analysis a provider would perform. - This note exists in a provider's project. A ``Discovery`` occurrence - is created in a consumer's project at the start of analysis. - - Attributes: - analysis_kind (grafeas.grafeas_v1.types.NoteKind): - Required. Immutable. The kind of analysis - that is handled by this discovery. - """ - - analysis_kind: common.NoteKind = proto.Field( - proto.ENUM, - number=1, - enum=common.NoteKind, - ) - - -class DiscoveryOccurrence(proto.Message): - r"""Provides information about the analysis status of a - discovered resource. - - Attributes: - continuous_analysis (grafeas.grafeas_v1.types.DiscoveryOccurrence.ContinuousAnalysis): - Whether the resource is continuously - analyzed. - analysis_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisStatus): - The status of discovery for the resource. - analysis_completed (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisCompleted): - - analysis_error (MutableSequence[google.rpc.status_pb2.Status]): - Indicates any errors encountered during - analysis of a resource. There could be 0 or more - of these errors. - analysis_status_error (google.rpc.status_pb2.Status): - When an error is encountered this will - contain a LocalizedMessage under details to show - to the user. The LocalizedMessage is output only - and populated by the API. - cpe (str): - The CPE of the resource being scanned. - last_scan_time (google.protobuf.timestamp_pb2.Timestamp): - The last time this resource was scanned. - archive_time (google.protobuf.timestamp_pb2.Timestamp): - The time occurrences related to this - discovery occurrence were archived. - sbom_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus): - The status of an SBOM generation. - vulnerability_attestation (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation): - The status of an vulnerability attestation - generation. - """ - - class ContinuousAnalysis(proto.Enum): - r"""Whether the resource is continuously analyzed. - - Values: - CONTINUOUS_ANALYSIS_UNSPECIFIED (0): - Unknown. - ACTIVE (1): - The resource is continuously analyzed. - INACTIVE (2): - The resource is ignored for continuous - analysis. - """ - CONTINUOUS_ANALYSIS_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class AnalysisStatus(proto.Enum): - r"""Analysis status for a resource. Currently for initial - analysis only (not updated in continuous analysis). - - Values: - ANALYSIS_STATUS_UNSPECIFIED (0): - Unknown. - PENDING (1): - Resource is known but no action has been - taken yet. - SCANNING (2): - Resource is being analyzed. - FINISHED_SUCCESS (3): - Analysis has finished successfully. - COMPLETE (3): - Analysis has completed. - FINISHED_FAILED (4): - Analysis has finished unsuccessfully, the - analysis itself is in a bad state. - FINISHED_UNSUPPORTED (5): - The resource is known not to be supported. - """ - _pb_options = {"allow_alias": True} - ANALYSIS_STATUS_UNSPECIFIED = 0 - PENDING = 1 - SCANNING = 2 - FINISHED_SUCCESS = 3 - COMPLETE = 3 - FINISHED_FAILED = 4 - FINISHED_UNSUPPORTED = 5 - - class AnalysisCompleted(proto.Message): - r"""Indicates which analysis completed successfully. Multiple - types of analysis can be performed on a single resource. - - Attributes: - analysis_type (MutableSequence[str]): - - """ - - analysis_type: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - class SBOMStatus(proto.Message): - r"""The status of an SBOM generation. - - Attributes: - sbom_state (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus.SBOMState): - The progress of the SBOM generation. - error (str): - If there was an error generating an SBOM, - this will indicate what that error was. - """ - - class SBOMState(proto.Enum): - r"""An enum indicating the progress of the SBOM generation. - - Values: - SBOM_STATE_UNSPECIFIED (0): - Default unknown state. - PENDING (1): - SBOM scanning is pending. - COMPLETE (2): - SBOM scanning has completed. - """ - SBOM_STATE_UNSPECIFIED = 0 - PENDING = 1 - COMPLETE = 2 - - sbom_state: "DiscoveryOccurrence.SBOMStatus.SBOMState" = proto.Field( - proto.ENUM, - number=1, - enum="DiscoveryOccurrence.SBOMStatus.SBOMState", - ) - error: str = proto.Field( - proto.STRING, - number=2, - ) - - class VulnerabilityAttestation(proto.Message): - r"""The status of an vulnerability attestation generation. - - Attributes: - last_attempt_time (google.protobuf.timestamp_pb2.Timestamp): - The last time we attempted to generate an - attestation. - state (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState): - The success/failure state of the latest - attestation attempt. - error (str): - If failure, the error reason for why the - attestation generation failed. - """ - - class VulnerabilityAttestationState(proto.Enum): - r"""An enum indicating the state of the attestation generation. - - Values: - VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED (0): - Default unknown state. - SUCCESS (1): - Attestation was successfully generated and - stored. - FAILURE (2): - Attestation was unsuccessfully generated and - stored. - """ - VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED = 0 - SUCCESS = 1 - FAILURE = 2 - - last_attempt_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - state: "DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState" = proto.Field( - proto.ENUM, - number=2, - enum="DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState", - ) - error: str = proto.Field( - proto.STRING, - number=3, - ) - - continuous_analysis: ContinuousAnalysis = proto.Field( - proto.ENUM, - number=1, - enum=ContinuousAnalysis, - ) - analysis_status: AnalysisStatus = proto.Field( - proto.ENUM, - number=2, - enum=AnalysisStatus, - ) - analysis_completed: AnalysisCompleted = proto.Field( - proto.MESSAGE, - number=7, - message=AnalysisCompleted, - ) - analysis_error: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=status_pb2.Status, - ) - analysis_status_error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - cpe: str = proto.Field( - proto.STRING, - number=4, - ) - last_scan_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - archive_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - sbom_status: SBOMStatus = proto.Field( - proto.MESSAGE, - number=9, - message=SBOMStatus, - ) - vulnerability_attestation: VulnerabilityAttestation = proto.Field( - proto.MESSAGE, - number=10, - message=VulnerabilityAttestation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py b/packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py deleted file mode 100644 index 5d3ca5c2c750..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import common, intoto_statement - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "DSSEAttestationNote", - "DSSEAttestationOccurrence", - }, -) - - -class DSSEAttestationNote(proto.Message): - r""" - - Attributes: - hint (grafeas.grafeas_v1.types.DSSEAttestationNote.DSSEHint): - DSSEHint hints at the purpose of the - attestation authority. - """ - - class DSSEHint(proto.Message): - r"""This submessage provides human-readable hints about the - purpose of the authority. Because the name of a note acts as its - resource reference, it is important to disambiguate the - canonical name of the Note (which might be a UUID for security - purposes) from "readable" names more suitable for debug output. - Note that these hints should not be used to look up authorities - in security sensitive contexts, such as when looking up - attestations to verify. - - Attributes: - human_readable_name (str): - Required. The human readable name of this - attestation authority, for example - "cloudbuild-prod". - """ - - human_readable_name: str = proto.Field( - proto.STRING, - number=1, - ) - - hint: DSSEHint = proto.Field( - proto.MESSAGE, - number=1, - message=DSSEHint, - ) - - -class DSSEAttestationOccurrence(proto.Message): - r"""Deprecated. Prefer to use a regular Occurrence, and populate - the Envelope at the top level of the Occurrence. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - envelope (grafeas.grafeas_v1.types.Envelope): - If doing something security critical, make - sure to verify the signatures in this metadata. - statement (grafeas.grafeas_v1.types.InTotoStatement): - - This field is a member of `oneof`_ ``decoded_payload``. - """ - - envelope: common.Envelope = proto.Field( - proto.MESSAGE, - number=1, - message=common.Envelope, - ) - statement: intoto_statement.InTotoStatement = proto.Field( - proto.MESSAGE, - number=2, - oneof="decoded_payload", - message=intoto_statement.InTotoStatement, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/grafeas.py b/packages/grafeas/grafeas/grafeas_v1/types/grafeas.py deleted file mode 100644 index b23a2a679a9b..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/grafeas.py +++ /dev/null @@ -1,941 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import attestation as g_attestation -from grafeas.grafeas_v1.types import build as g_build -from grafeas.grafeas_v1.types import common -from grafeas.grafeas_v1.types import compliance as g_compliance -from grafeas.grafeas_v1.types import deployment as g_deployment -from grafeas.grafeas_v1.types import discovery as g_discovery -from grafeas.grafeas_v1.types import dsse_attestation as g_dsse_attestation -from grafeas.grafeas_v1.types import image as g_image -from grafeas.grafeas_v1.types import package as g_package -from grafeas.grafeas_v1.types import sbom -from grafeas.grafeas_v1.types import secret as g_secret -from grafeas.grafeas_v1.types import upgrade as g_upgrade -from grafeas.grafeas_v1.types import vex -from grafeas.grafeas_v1.types import vulnerability as g_vulnerability - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "Occurrence", - "Note", - "GetOccurrenceRequest", - "ListOccurrencesRequest", - "ListOccurrencesResponse", - "DeleteOccurrenceRequest", - "CreateOccurrenceRequest", - "UpdateOccurrenceRequest", - "GetNoteRequest", - "GetOccurrenceNoteRequest", - "ListNotesRequest", - "ListNotesResponse", - "DeleteNoteRequest", - "CreateNoteRequest", - "UpdateNoteRequest", - "ListNoteOccurrencesRequest", - "ListNoteOccurrencesResponse", - "BatchCreateNotesRequest", - "BatchCreateNotesResponse", - "BatchCreateOccurrencesRequest", - "BatchCreateOccurrencesResponse", - }, -) - - -class Occurrence(proto.Message): - r"""An instance of an analysis type that has been found on a - resource. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - resource_uri (str): - Required. Immutable. A URI that represents the resource for - which the occurrence applies. For example, - ``https://gcr.io/project/image@sha256:123abc`` for a Docker - image. - note_name (str): - Required. Immutable. The analysis note associated with this - occurrence, in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. This field can - be used as a filter in list requests. - kind (grafeas.grafeas_v1.types.NoteKind): - Output only. This explicitly denotes which of - the occurrence details are specified. This field - can be used as a filter in list requests. - remediation (str): - A description of actions that can be taken to - remedy the note. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this occurrence was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this occurrence was - last updated. - vulnerability (grafeas.grafeas_v1.types.VulnerabilityOccurrence): - Describes a security vulnerability. - - This field is a member of `oneof`_ ``details``. - build (grafeas.grafeas_v1.types.BuildOccurrence): - Describes a verifiable build. - - This field is a member of `oneof`_ ``details``. - image (grafeas.grafeas_v1.types.ImageOccurrence): - Describes how this resource derives from the - basis in the associated note. - - This field is a member of `oneof`_ ``details``. - package (grafeas.grafeas_v1.types.PackageOccurrence): - Describes the installation of a package on - the linked resource. - - This field is a member of `oneof`_ ``details``. - deployment (grafeas.grafeas_v1.types.DeploymentOccurrence): - Describes the deployment of an artifact on a - runtime. - - This field is a member of `oneof`_ ``details``. - discovery (grafeas.grafeas_v1.types.DiscoveryOccurrence): - Describes when a resource was discovered. - - This field is a member of `oneof`_ ``details``. - attestation (grafeas.grafeas_v1.types.AttestationOccurrence): - Describes an attestation of an artifact. - - This field is a member of `oneof`_ ``details``. - upgrade (grafeas.grafeas_v1.types.UpgradeOccurrence): - Describes an available package upgrade on the - linked resource. - - This field is a member of `oneof`_ ``details``. - compliance (grafeas.grafeas_v1.types.ComplianceOccurrence): - Describes a compliance violation on a linked - resource. - - This field is a member of `oneof`_ ``details``. - dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationOccurrence): - Describes an attestation of an artifact using - dsse. - - This field is a member of `oneof`_ ``details``. - sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceOccurrence): - Describes a specific SBOM reference - occurrences. - - This field is a member of `oneof`_ ``details``. - secret (grafeas.grafeas_v1.types.SecretOccurrence): - Describes a secret. - - This field is a member of `oneof`_ ``details``. - envelope (grafeas.grafeas_v1.types.Envelope): - https://github.com/secure-systems-lab/dsse - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=2, - ) - note_name: str = proto.Field( - proto.STRING, - number=3, - ) - kind: common.NoteKind = proto.Field( - proto.ENUM, - number=4, - enum=common.NoteKind, - ) - remediation: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - vulnerability: g_vulnerability.VulnerabilityOccurrence = proto.Field( - proto.MESSAGE, - number=8, - oneof="details", - message=g_vulnerability.VulnerabilityOccurrence, - ) - build: g_build.BuildOccurrence = proto.Field( - proto.MESSAGE, - number=9, - oneof="details", - message=g_build.BuildOccurrence, - ) - image: g_image.ImageOccurrence = proto.Field( - proto.MESSAGE, - number=10, - oneof="details", - message=g_image.ImageOccurrence, - ) - package: g_package.PackageOccurrence = proto.Field( - proto.MESSAGE, - number=11, - oneof="details", - message=g_package.PackageOccurrence, - ) - deployment: g_deployment.DeploymentOccurrence = proto.Field( - proto.MESSAGE, - number=12, - oneof="details", - message=g_deployment.DeploymentOccurrence, - ) - discovery: g_discovery.DiscoveryOccurrence = proto.Field( - proto.MESSAGE, - number=13, - oneof="details", - message=g_discovery.DiscoveryOccurrence, - ) - attestation: g_attestation.AttestationOccurrence = proto.Field( - proto.MESSAGE, - number=14, - oneof="details", - message=g_attestation.AttestationOccurrence, - ) - upgrade: g_upgrade.UpgradeOccurrence = proto.Field( - proto.MESSAGE, - number=15, - oneof="details", - message=g_upgrade.UpgradeOccurrence, - ) - compliance: g_compliance.ComplianceOccurrence = proto.Field( - proto.MESSAGE, - number=16, - oneof="details", - message=g_compliance.ComplianceOccurrence, - ) - dsse_attestation: g_dsse_attestation.DSSEAttestationOccurrence = proto.Field( - proto.MESSAGE, - number=17, - oneof="details", - message=g_dsse_attestation.DSSEAttestationOccurrence, - ) - sbom_reference: sbom.SBOMReferenceOccurrence = proto.Field( - proto.MESSAGE, - number=19, - oneof="details", - message=sbom.SBOMReferenceOccurrence, - ) - secret: g_secret.SecretOccurrence = proto.Field( - proto.MESSAGE, - number=20, - oneof="details", - message=g_secret.SecretOccurrence, - ) - envelope: common.Envelope = proto.Field( - proto.MESSAGE, - number=18, - message=common.Envelope, - ) - - -class Note(proto.Message): - r"""A type of analysis that can be done for a resource. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - short_description (str): - A one sentence description of this note. - long_description (str): - A detailed description of this note. - kind (grafeas.grafeas_v1.types.NoteKind): - Output only. The type of analysis. This field - can be used as a filter in list requests. - related_url (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - URLs associated with this note. - expiration_time (google.protobuf.timestamp_pb2.Timestamp): - Time of expiration for this note. Empty if - note does not expire. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this note was created. - This field can be used as a filter in list - requests. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this note was last - updated. This field can be used as a filter in - list requests. - related_note_names (MutableSequence[str]): - Other notes related to this note. - vulnerability (grafeas.grafeas_v1.types.VulnerabilityNote): - A note describing a package vulnerability. - - This field is a member of `oneof`_ ``type``. - build (grafeas.grafeas_v1.types.BuildNote): - A note describing build provenance for a - verifiable build. - - This field is a member of `oneof`_ ``type``. - image (grafeas.grafeas_v1.types.ImageNote): - A note describing a base image. - - This field is a member of `oneof`_ ``type``. - package (grafeas.grafeas_v1.types.PackageNote): - A note describing a package hosted by various - package managers. - - This field is a member of `oneof`_ ``type``. - deployment (grafeas.grafeas_v1.types.DeploymentNote): - A note describing something that can be - deployed. - - This field is a member of `oneof`_ ``type``. - discovery (grafeas.grafeas_v1.types.DiscoveryNote): - A note describing the initial analysis of a - resource. - - This field is a member of `oneof`_ ``type``. - attestation (grafeas.grafeas_v1.types.AttestationNote): - A note describing an attestation role. - - This field is a member of `oneof`_ ``type``. - upgrade (grafeas.grafeas_v1.types.UpgradeNote): - A note describing available package upgrades. - - This field is a member of `oneof`_ ``type``. - compliance (grafeas.grafeas_v1.types.ComplianceNote): - A note describing a compliance check. - - This field is a member of `oneof`_ ``type``. - dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationNote): - A note describing a dsse attestation note. - - This field is a member of `oneof`_ ``type``. - vulnerability_assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote): - A note describing a vulnerability assessment. - - This field is a member of `oneof`_ ``type``. - sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceNote): - A note describing an SBOM reference. - - This field is a member of `oneof`_ ``type``. - secret (grafeas.grafeas_v1.types.SecretNote): - A note describing a secret. - - This field is a member of `oneof`_ ``type``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - short_description: str = proto.Field( - proto.STRING, - number=2, - ) - long_description: str = proto.Field( - proto.STRING, - number=3, - ) - kind: common.NoteKind = proto.Field( - proto.ENUM, - number=4, - enum=common.NoteKind, - ) - related_url: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=common.RelatedUrl, - ) - expiration_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - related_note_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=9, - ) - vulnerability: g_vulnerability.VulnerabilityNote = proto.Field( - proto.MESSAGE, - number=10, - oneof="type", - message=g_vulnerability.VulnerabilityNote, - ) - build: g_build.BuildNote = proto.Field( - proto.MESSAGE, - number=11, - oneof="type", - message=g_build.BuildNote, - ) - image: g_image.ImageNote = proto.Field( - proto.MESSAGE, - number=12, - oneof="type", - message=g_image.ImageNote, - ) - package: g_package.PackageNote = proto.Field( - proto.MESSAGE, - number=13, - oneof="type", - message=g_package.PackageNote, - ) - deployment: g_deployment.DeploymentNote = proto.Field( - proto.MESSAGE, - number=14, - oneof="type", - message=g_deployment.DeploymentNote, - ) - discovery: g_discovery.DiscoveryNote = proto.Field( - proto.MESSAGE, - number=15, - oneof="type", - message=g_discovery.DiscoveryNote, - ) - attestation: g_attestation.AttestationNote = proto.Field( - proto.MESSAGE, - number=16, - oneof="type", - message=g_attestation.AttestationNote, - ) - upgrade: g_upgrade.UpgradeNote = proto.Field( - proto.MESSAGE, - number=17, - oneof="type", - message=g_upgrade.UpgradeNote, - ) - compliance: g_compliance.ComplianceNote = proto.Field( - proto.MESSAGE, - number=18, - oneof="type", - message=g_compliance.ComplianceNote, - ) - dsse_attestation: g_dsse_attestation.DSSEAttestationNote = proto.Field( - proto.MESSAGE, - number=19, - oneof="type", - message=g_dsse_attestation.DSSEAttestationNote, - ) - vulnerability_assessment: vex.VulnerabilityAssessmentNote = proto.Field( - proto.MESSAGE, - number=20, - oneof="type", - message=vex.VulnerabilityAssessmentNote, - ) - sbom_reference: sbom.SBOMReferenceNote = proto.Field( - proto.MESSAGE, - number=21, - oneof="type", - message=sbom.SBOMReferenceNote, - ) - secret: g_secret.SecretNote = proto.Field( - proto.MESSAGE, - number=22, - oneof="type", - message=g_secret.SecretNote, - ) - - -class GetOccurrenceRequest(proto.Message): - r"""Request to get an occurrence. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListOccurrencesRequest(proto.Message): - r"""Request to list occurrences. - - Attributes: - parent (str): - The name of the project to list occurrences for in the form - of ``projects/[PROJECT_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of occurrences to return in the list. - Must be positive. Max allowed page size is 1000. - If not specified, page size defaults to 20. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListOccurrencesResponse(proto.Message): - r"""Response for listing occurrences. - - Attributes: - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences requested. - next_page_token (str): - The next pagination token in the list response. It should be - used as ``page_token`` for the following request. An empty - value means no more results. - """ - - @property - def raw_page(self): - return self - - occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Occurrence", - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteOccurrenceRequest(proto.Message): - r"""Request to delete an occurrence. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateOccurrenceRequest(proto.Message): - r"""Request to create a new occurrence. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrence is to - be created. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The occurrence to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - occurrence: "Occurrence" = proto.Field( - proto.MESSAGE, - number=2, - message="Occurrence", - ) - - -class UpdateOccurrenceRequest(proto.Message): - r"""Request to update an occurrence. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - occurrence (grafeas.grafeas_v1.types.Occurrence): - The updated occurrence. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - occurrence: "Occurrence" = proto.Field( - proto.MESSAGE, - number=2, - message="Occurrence", - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class GetNoteRequest(proto.Message): - r"""Request to get a note. - - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOccurrenceNoteRequest(proto.Message): - r"""Request to get the note to which the specified occurrence is - attached. - - Attributes: - name (str): - The name of the occurrence in the form of - ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListNotesRequest(proto.Message): - r"""Request to list notes. - - Attributes: - parent (str): - The name of the project to list notes for in the form of - ``projects/[PROJECT_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of notes to return in the list. Must - be positive. Max allowed page size is 1000. If - not specified, page size defaults to 20. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListNotesResponse(proto.Message): - r"""Response for listing notes. - - Attributes: - notes (MutableSequence[grafeas.grafeas_v1.types.Note]): - The notes requested. - next_page_token (str): - The next pagination token in the list response. It should be - used as ``page_token`` for the following request. An empty - value means no more results. - """ - - @property - def raw_page(self): - return self - - notes: MutableSequence["Note"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Note", - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteNoteRequest(proto.Message): - r"""Request to delete a note. - - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateNoteRequest(proto.Message): - r"""Request to create a new note. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the note is to be - created. - note_id (str): - The ID to use for this note. - note (grafeas.grafeas_v1.types.Note): - The note to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - note_id: str = proto.Field( - proto.STRING, - number=2, - ) - note: "Note" = proto.Field( - proto.MESSAGE, - number=3, - message="Note", - ) - - -class UpdateNoteRequest(proto.Message): - r"""Request to update a note. - - Attributes: - name (str): - The name of the note in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - note (grafeas.grafeas_v1.types.Note): - The updated note. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields to update. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - note: "Note" = proto.Field( - proto.MESSAGE, - number=2, - message="Note", - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ListNoteOccurrencesRequest(proto.Message): - r"""Request to list occurrences for a note. - - Attributes: - name (str): - The name of the note to list occurrences for in the form of - ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. - filter (str): - The filter expression. - page_size (int): - Number of occurrences to return in the list. - page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListNoteOccurrencesResponse(proto.Message): - r"""Response for listing occurrences for a note. - - Attributes: - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences attached to the specified - note. - next_page_token (str): - Token to provide to skip to a particular spot - in the list. - """ - - @property - def raw_page(self): - return self - - occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Occurrence", - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchCreateNotesRequest(proto.Message): - r"""Request to create notes in batch. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the notes are to be - created. - notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): - The notes to create. Max allowed length is - 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - notes: MutableMapping[str, "Note"] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message="Note", - ) - - -class BatchCreateNotesResponse(proto.Message): - r"""Response for creating notes in batch. - - Attributes: - notes (MutableSequence[grafeas.grafeas_v1.types.Note]): - The notes that were created. - """ - - notes: MutableSequence["Note"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Note", - ) - - -class BatchCreateOccurrencesRequest(proto.Message): - r"""Request to create occurrences in batch. - - Attributes: - parent (str): - The name of the project in the form of - ``projects/[PROJECT_ID]``, under which the occurrences are - to be created. - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences to create. Max allowed length - is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Occurrence", - ) - - -class BatchCreateOccurrencesResponse(proto.Message): - r"""Response for creating occurrences in batch. - - Attributes: - occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): - The occurrences that were created. - """ - - occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Occurrence", - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/image.py b/packages/grafeas/grafeas/grafeas_v1/types/image.py deleted file mode 100644 index f316aad20caf..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/image.py +++ /dev/null @@ -1,157 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "Layer", - "Fingerprint", - "ImageNote", - "ImageOccurrence", - }, -) - - -class Layer(proto.Message): - r"""Layer holds metadata specific to a layer of a Docker image. - - Attributes: - directive (str): - Required. The recovered Dockerfile directive - used to construct this layer. See - https://docs.docker.com/engine/reference/builder/ - for more information. - arguments (str): - The recovered arguments to the Dockerfile - directive. - """ - - directive: str = proto.Field( - proto.STRING, - number=1, - ) - arguments: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Fingerprint(proto.Message): - r"""A set of properties that uniquely identify a given Docker - image. - - Attributes: - v1_name (str): - Required. The layer ID of the final layer in - the Docker image's v1 representation. - v2_blob (MutableSequence[str]): - Required. The ordered list of v2 blobs that - represent a given image. - v2_name (str): - Output only. The name of the image's v2 blobs computed via: - [bottom] := v2_blob[bottom] [N] := sha256(v2_blob[N] + " " + - v2_name[N+1]) Only the name of the final blob is kept. - """ - - v1_name: str = proto.Field( - proto.STRING, - number=1, - ) - v2_blob: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - v2_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ImageNote(proto.Message): - r"""Basis describes the base image portion (Note) of the DockerImage - relationship. Linked occurrences are derived from this or an - equivalent image via: FROM Or an equivalent - reference, e.g., a tag of the resource_url. - - Attributes: - resource_url (str): - Required. Immutable. The resource_url for the resource - representing the basis of associated occurrence images. - fingerprint (grafeas.grafeas_v1.types.Fingerprint): - Required. Immutable. The fingerprint of the - base image. - """ - - resource_url: str = proto.Field( - proto.STRING, - number=1, - ) - fingerprint: "Fingerprint" = proto.Field( - proto.MESSAGE, - number=2, - message="Fingerprint", - ) - - -class ImageOccurrence(proto.Message): - r"""Details of the derived image portion of the DockerImage - relationship. This image would be produced from a Dockerfile - with FROM . - - Attributes: - fingerprint (grafeas.grafeas_v1.types.Fingerprint): - Required. The fingerprint of the derived - image. - distance (int): - Output only. The number of layers by which - this image differs from the associated image - basis. - layer_info (MutableSequence[grafeas.grafeas_v1.types.Layer]): - This contains layer-specific metadata, if populated it has - length "distance" and is ordered with [distance] being the - layer immediately following the base image and [1] being the - final layer. - base_resource_url (str): - Output only. This contains the base image URL - for the derived image occurrence. - """ - - fingerprint: "Fingerprint" = proto.Field( - proto.MESSAGE, - number=1, - message="Fingerprint", - ) - distance: int = proto.Field( - proto.INT32, - number=2, - ) - layer_info: MutableSequence["Layer"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Layer", - ) - base_resource_url: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py b/packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py deleted file mode 100644 index 08112fbc7e8e..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py +++ /dev/null @@ -1,246 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "Recipe", - "Completeness", - "Metadata", - "BuilderConfig", - "InTotoProvenance", - }, -) - - -class Recipe(proto.Message): - r"""Steps taken to build the artifact. - For a TaskRun, typically each container corresponds to one step - in the recipe. - - Attributes: - type_ (str): - URI indicating what type of recipe was - performed. It determines the meaning of - recipe.entryPoint, recipe.arguments, - recipe.environment, and materials. - defined_in_material (int): - Index in materials containing the recipe - steps that are not implied by recipe.type. For - example, if the recipe type were "make", then - this would point to the source containing the - Makefile, not the make program itself. Set to -1 - if the recipe doesn't come from a material, as - zero is default unset value for int64. - entry_point (str): - String identifying the entry point into the - build. This is often a path to a configuration - file and/or a target label within that file. The - syntax and meaning are defined by recipe.type. - For example, if the recipe type were "make", - then this would reference the directory in which - to run make as well as which target to use. - arguments (MutableSequence[google.protobuf.any_pb2.Any]): - Collection of all external inputs that - influenced the build on top of - recipe.definedInMaterial and recipe.entryPoint. - For example, if the recipe type were "make", - then this might be the flags passed to make - aside from the target, which is captured in - recipe.entryPoint. Since the arguments field can - greatly vary in structure, depending on the - builder and recipe type, this is of form "Any". - environment (MutableSequence[google.protobuf.any_pb2.Any]): - Any other builder-controlled inputs necessary - for correctly evaluating the recipe. Usually - only needed for reproducing the build but not - evaluated as part of policy. Since the - environment field can greatly vary in structure, - depending on the builder and recipe type, this - is of form "Any". - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - defined_in_material: int = proto.Field( - proto.INT64, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - arguments: MutableSequence[any_pb2.Any] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=any_pb2.Any, - ) - environment: MutableSequence[any_pb2.Any] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=any_pb2.Any, - ) - - -class Completeness(proto.Message): - r"""Indicates that the builder claims certain fields in this - message to be complete. - - Attributes: - arguments (bool): - If true, the builder claims that - recipe.arguments is complete, meaning that all - external inputs are properly captured in the - recipe. - environment (bool): - If true, the builder claims that - recipe.environment is claimed to be complete. - materials (bool): - If true, the builder claims that materials - are complete, usually through some controls to - prevent network access. Sometimes called - "hermetic". - """ - - arguments: bool = proto.Field( - proto.BOOL, - number=1, - ) - environment: bool = proto.Field( - proto.BOOL, - number=2, - ) - materials: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Metadata(proto.Message): - r"""Other properties of the build. - - Attributes: - build_invocation_id (str): - Identifies the particular build invocation, - which can be useful for finding associated logs - or other ad-hoc analysis. The value SHOULD be - globally unique, per in-toto Provenance spec. - build_started_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build started. - build_finished_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build completed. - completeness (grafeas.grafeas_v1.types.Completeness): - Indicates that the builder claims certain - fields in this message to be complete. - reproducible (bool): - If true, the builder claims that running the - recipe on materials will produce bit-for-bit - identical output. - """ - - build_invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - build_started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - build_finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - completeness: "Completeness" = proto.Field( - proto.MESSAGE, - number=4, - message="Completeness", - ) - reproducible: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class BuilderConfig(proto.Message): - r""" - - Attributes: - id (str): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InTotoProvenance(proto.Message): - r""" - - Attributes: - builder_config (grafeas.grafeas_v1.types.BuilderConfig): - required - recipe (grafeas.grafeas_v1.types.Recipe): - Identifies the configuration used for the - build. When combined with materials, this SHOULD - fully describe the build, such that re-running - this recipe results in bit-for-bit identical - output (if the build is reproducible). - metadata (grafeas.grafeas_v1.types.Metadata): - - materials (MutableSequence[str]): - The collection of artifacts that influenced - the build including sources, dependencies, build - tools, base images, and so on. This is - considered to be incomplete unless - metadata.completeness.materials is true. Unset - or null is equivalent to empty. - """ - - builder_config: "BuilderConfig" = proto.Field( - proto.MESSAGE, - number=1, - message="BuilderConfig", - ) - recipe: "Recipe" = proto.Field( - proto.MESSAGE, - number=2, - message="Recipe", - ) - metadata: "Metadata" = proto.Field( - proto.MESSAGE, - number=3, - message="Metadata", - ) - materials: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py b/packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py deleted file mode 100644 index be85f5a36643..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py +++ /dev/null @@ -1,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import ( - slsa_provenance_zero_two as g_slsa_provenance_zero_two, -) -from grafeas.grafeas_v1.types import intoto_provenance -from grafeas.grafeas_v1.types import slsa_provenance as g_slsa_provenance - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "InTotoStatement", - "Subject", - "InTotoSlsaProvenanceV1", - }, -) - - -class InTotoStatement(proto.Message): - r"""Spec defined at - https://github.com/in-toto/attestation/tree/main/spec#statement - The serialized InTotoStatement will be stored as - Envelope.payload. Envelope.payloadType is always - "application/vnd.in-toto+json". - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (str): - Always ``https://in-toto.io/Statement/v0.1``. - subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): - - predicate_type (str): - ``https://slsa.dev/provenance/v0.1`` for SlsaProvenance. - provenance (grafeas.grafeas_v1.types.InTotoProvenance): - - This field is a member of `oneof`_ ``predicate``. - slsa_provenance (grafeas.grafeas_v1.types.SlsaProvenance): - - This field is a member of `oneof`_ ``predicate``. - slsa_provenance_zero_two (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo): - - This field is a member of `oneof`_ ``predicate``. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - subject: MutableSequence["Subject"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Subject", - ) - predicate_type: str = proto.Field( - proto.STRING, - number=3, - ) - provenance: intoto_provenance.InTotoProvenance = proto.Field( - proto.MESSAGE, - number=4, - oneof="predicate", - message=intoto_provenance.InTotoProvenance, - ) - slsa_provenance: g_slsa_provenance.SlsaProvenance = proto.Field( - proto.MESSAGE, - number=5, - oneof="predicate", - message=g_slsa_provenance.SlsaProvenance, - ) - slsa_provenance_zero_two: g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo = ( - proto.Field( - proto.MESSAGE, - number=6, - oneof="predicate", - message=g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo, - ) - ) - - -class Subject(proto.Message): - r""" - - Attributes: - name (str): - - digest (MutableMapping[str, str]): - ``"": ""`` Algorithms can be e.g. - sha256, sha512 See - https://github.com/in-toto/attestation/blob/main/spec/field_types.md#DigestSet - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class InTotoSlsaProvenanceV1(proto.Message): - r""" - - Attributes: - type_ (str): - InToto spec defined at - https://github.com/in-toto/attestation/tree/main/spec#statement - subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): - - predicate_type (str): - - predicate (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.SlsaProvenanceV1): - - """ - - class SlsaProvenanceV1(proto.Message): - r"""Keep in sync with schema at - https://github.com/slsa-framework/slsa/blob/main/docs/provenance/schema/v1/provenance.proto - Builder renamed to ProvenanceBuilder because of Java conflicts. - - Attributes: - build_definition (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildDefinition): - - run_details (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.RunDetails): - - """ - - build_definition: "InTotoSlsaProvenanceV1.BuildDefinition" = proto.Field( - proto.MESSAGE, - number=1, - message="InTotoSlsaProvenanceV1.BuildDefinition", - ) - run_details: "InTotoSlsaProvenanceV1.RunDetails" = proto.Field( - proto.MESSAGE, - number=2, - message="InTotoSlsaProvenanceV1.RunDetails", - ) - - class BuildDefinition(proto.Message): - r""" - - Attributes: - build_type (str): - - external_parameters (google.protobuf.struct_pb2.Struct): - - internal_parameters (google.protobuf.struct_pb2.Struct): - - resolved_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): - - """ - - build_type: str = proto.Field( - proto.STRING, - number=1, - ) - external_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - internal_parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - resolved_dependencies: MutableSequence[ - "InTotoSlsaProvenanceV1.ResourceDescriptor" - ] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message="InTotoSlsaProvenanceV1.ResourceDescriptor", - ) - - class ResourceDescriptor(proto.Message): - r""" - - Attributes: - name (str): - - uri (str): - - digest (MutableMapping[str, str]): - - content (bytes): - - download_location (str): - - media_type (str): - - annotations (MutableMapping[str, google.protobuf.struct_pb2.Value]): - - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - content: bytes = proto.Field( - proto.BYTES, - number=4, - ) - download_location: str = proto.Field( - proto.STRING, - number=5, - ) - media_type: str = proto.Field( - proto.STRING, - number=6, - ) - annotations: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - - class RunDetails(proto.Message): - r""" - - Attributes: - builder (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ProvenanceBuilder): - - metadata (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildMetadata): - - byproducts (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): - - """ - - builder: "InTotoSlsaProvenanceV1.ProvenanceBuilder" = proto.Field( - proto.MESSAGE, - number=1, - message="InTotoSlsaProvenanceV1.ProvenanceBuilder", - ) - metadata: "InTotoSlsaProvenanceV1.BuildMetadata" = proto.Field( - proto.MESSAGE, - number=2, - message="InTotoSlsaProvenanceV1.BuildMetadata", - ) - byproducts: MutableSequence[ - "InTotoSlsaProvenanceV1.ResourceDescriptor" - ] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="InTotoSlsaProvenanceV1.ResourceDescriptor", - ) - - class ProvenanceBuilder(proto.Message): - r""" - - Attributes: - id (str): - - version (MutableMapping[str, str]): - - builder_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - version: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - builder_dependencies: MutableSequence[ - "InTotoSlsaProvenanceV1.ResourceDescriptor" - ] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="InTotoSlsaProvenanceV1.ResourceDescriptor", - ) - - class BuildMetadata(proto.Message): - r""" - - Attributes: - invocation_id (str): - - started_on (google.protobuf.timestamp_pb2.Timestamp): - - finished_on (google.protobuf.timestamp_pb2.Timestamp): - - """ - - invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - subject: MutableSequence["Subject"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Subject", - ) - predicate_type: str = proto.Field( - proto.STRING, - number=3, - ) - predicate: SlsaProvenanceV1 = proto.Field( - proto.MESSAGE, - number=4, - message=SlsaProvenanceV1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/package.py b/packages/grafeas/grafeas/grafeas_v1/types/package.py deleted file mode 100644 index 7af0773ef0fc..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/package.py +++ /dev/null @@ -1,378 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import common - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "Architecture", - "Distribution", - "Location", - "PackageNote", - "PackageOccurrence", - "Version", - }, -) - - -class Architecture(proto.Enum): - r"""Instruction set architectures supported by various package - managers. - - Values: - ARCHITECTURE_UNSPECIFIED (0): - Unknown architecture. - X86 (1): - X86 architecture. - X64 (2): - X64 architecture. - """ - ARCHITECTURE_UNSPECIFIED = 0 - X86 = 1 - X64 = 2 - - -class Distribution(proto.Message): - r"""This represents a particular channel of distribution for a - given package. E.g., Debian's jessie-backports dpkg mirror. - - Attributes: - cpe_uri (str): - The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - latest_version (grafeas.grafeas_v1.types.Version): - The latest available version of this package - in this distribution channel. - maintainer (str): - A freeform string denoting the maintainer of - this package. - url (str): - The distribution channel-specific homepage - for this package. - description (str): - The distribution channel-specific description - of this package. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - architecture: "Architecture" = proto.Field( - proto.ENUM, - number=2, - enum="Architecture", - ) - latest_version: "Version" = proto.Field( - proto.MESSAGE, - number=3, - message="Version", - ) - maintainer: str = proto.Field( - proto.STRING, - number=4, - ) - url: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - - -class Location(proto.Message): - r"""An occurrence of a particular package installation found within a - system's filesystem. E.g., glibc was found in - ``/var/lib/dpkg/status``. - - Attributes: - cpe_uri (str): - Deprecated. The CPE URI in `CPE - format `__ - version (grafeas.grafeas_v1.types.Version): - Deprecated. - The version installed at this location. - path (str): - The path from which we gathered that this - package/version is installed. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - version: "Version" = proto.Field( - proto.MESSAGE, - number=2, - message="Version", - ) - path: str = proto.Field( - proto.STRING, - number=3, - ) - - -class PackageNote(proto.Message): - r"""PackageNote represents a particular package version. - - Attributes: - name (str): - The name of the package. - distribution (MutableSequence[grafeas.grafeas_v1.types.Distribution]): - Deprecated. - The various channels by which a package is - distributed. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - cpe_uri (str): - The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. The - cpe_uri will be blank for language packages. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - Architecture will be blank for language - packages. - version (grafeas.grafeas_v1.types.Version): - The version of the package. - maintainer (str): - A freeform text denoting the maintainer of - this package. - url (str): - The homepage for this package. - description (str): - The description of this package. - license_ (grafeas.grafeas_v1.types.License): - Licenses that have been declared by the - authors of the package. - digest (MutableSequence[grafeas.grafeas_v1.types.Digest]): - Hash value, typically a file digest, that - allows unique identification a specific package. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - distribution: MutableSequence["Distribution"] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message="Distribution", - ) - package_type: str = proto.Field( - proto.STRING, - number=11, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=12, - ) - architecture: "Architecture" = proto.Field( - proto.ENUM, - number=13, - enum="Architecture", - ) - version: "Version" = proto.Field( - proto.MESSAGE, - number=14, - message="Version", - ) - maintainer: str = proto.Field( - proto.STRING, - number=15, - ) - url: str = proto.Field( - proto.STRING, - number=16, - ) - description: str = proto.Field( - proto.STRING, - number=17, - ) - license_: common.License = proto.Field( - proto.MESSAGE, - number=18, - message=common.License, - ) - digest: MutableSequence[common.Digest] = proto.RepeatedField( - proto.MESSAGE, - number=19, - message=common.Digest, - ) - - -class PackageOccurrence(proto.Message): - r"""Details on how a particular software package was installed on - a system. - - Attributes: - name (str): - The name of the installed package. - location (MutableSequence[grafeas.grafeas_v1.types.Location]): - All of the places within the filesystem - versions of this package have been found. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - cpe_uri (str): - The cpe_uri in `CPE - format `__ denoting - the package manager version distributing a package. The - cpe_uri will be blank for language packages. - architecture (grafeas.grafeas_v1.types.Architecture): - The CPU architecture for which packages in - this distribution channel were built. - Architecture will be blank for language - packages. - license_ (grafeas.grafeas_v1.types.License): - Licenses that have been declared by the - authors of the package. - version (grafeas.grafeas_v1.types.Version): - The version of the package. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - location: MutableSequence["Location"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="Location", - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=4, - ) - architecture: "Architecture" = proto.Field( - proto.ENUM, - number=5, - enum="Architecture", - ) - license_: common.License = proto.Field( - proto.MESSAGE, - number=6, - message=common.License, - ) - version: "Version" = proto.Field( - proto.MESSAGE, - number=7, - message="Version", - ) - - -class Version(proto.Message): - r"""Version contains structured information about the version of - a package. - - Attributes: - epoch (int): - Used to correct mistakes in the version - numbering scheme. - name (str): - Required only when version kind is NORMAL. - The main part of the version name. - revision (str): - The iteration of the package build from the - above version. - inclusive (bool): - Whether this version is specifying part of an - inclusive range. Grafeas does not have the - capability to specify version ranges; instead we - have fields that specify start version and end - versions. At times this is insufficient - we - also need to specify whether the version is - included in the range or is excluded from the - range. This boolean is expected to be set to - true when the version is included in a range. - kind (grafeas.grafeas_v1.types.Version.VersionKind): - Required. Distinguishes between sentinel - MIN/MAX versions and normal versions. - full_name (str): - Human readable version string. This string is - of the form :- and is - only set when kind is NORMAL. - """ - - class VersionKind(proto.Enum): - r"""Whether this is an ordinary package version or a sentinel - MIN/MAX version. - - Values: - VERSION_KIND_UNSPECIFIED (0): - Unknown. - NORMAL (1): - A standard package version. - MINIMUM (2): - A special version representing negative - infinity. - MAXIMUM (3): - A special version representing positive - infinity. - """ - VERSION_KIND_UNSPECIFIED = 0 - NORMAL = 1 - MINIMUM = 2 - MAXIMUM = 3 - - epoch: int = proto.Field( - proto.INT32, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - revision: str = proto.Field( - proto.STRING, - number=3, - ) - inclusive: bool = proto.Field( - proto.BOOL, - number=6, - ) - kind: VersionKind = proto.Field( - proto.ENUM, - number=4, - enum=VersionKind, - ) - full_name: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/provenance.py b/packages/grafeas/grafeas/grafeas_v1/types/provenance.py deleted file mode 100644 index 35ee483a7b6b..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/provenance.py +++ /dev/null @@ -1,596 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "BuildProvenance", - "Source", - "FileHashes", - "Hash", - "Command", - "Artifact", - "SourceContext", - "AliasContext", - "CloudRepoSourceContext", - "GerritSourceContext", - "GitSourceContext", - "RepoId", - "ProjectRepoId", - }, -) - - -class BuildProvenance(proto.Message): - r"""Provenance of a build. Contains all information needed to - verify the full details about the build from source to - completion. - - Attributes: - id (str): - Required. Unique identifier of the build. - project_id (str): - ID of the project. - commands (MutableSequence[grafeas.grafeas_v1.types.Command]): - Commands requested by the build. - built_artifacts (MutableSequence[grafeas.grafeas_v1.types.Artifact]): - Output of the build. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the build was created. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which execution of the build was - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which execution of the build was - finished. - creator (str): - E-mail address of the user who initiated this - build. Note that this was the user's e-mail - address at the time the build was initiated; - this address may not represent the same end-user - for all time. - logs_uri (str): - URI where any logs for this provenance were - written. - source_provenance (grafeas.grafeas_v1.types.Source): - Details of the Source input to the build. - trigger_id (str): - Trigger identifier if the build was triggered - automatically; empty if not. - build_options (MutableMapping[str, str]): - Special options applied to this build. This - is a catch-all field where build providers can - enter any desired additional details. - builder_version (str): - Version string of the builder at the time - this build was executed. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - project_id: str = proto.Field( - proto.STRING, - number=2, - ) - commands: MutableSequence["Command"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="Command", - ) - built_artifacts: MutableSequence["Artifact"] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message="Artifact", - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - creator: str = proto.Field( - proto.STRING, - number=8, - ) - logs_uri: str = proto.Field( - proto.STRING, - number=9, - ) - source_provenance: "Source" = proto.Field( - proto.MESSAGE, - number=10, - message="Source", - ) - trigger_id: str = proto.Field( - proto.STRING, - number=11, - ) - build_options: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - builder_version: str = proto.Field( - proto.STRING, - number=13, - ) - - -class Source(proto.Message): - r"""Source describes the location of the source used for the - build. - - Attributes: - artifact_storage_source_uri (str): - If provided, the input binary artifacts for - the build came from this location. - file_hashes (MutableMapping[str, grafeas.grafeas_v1.types.FileHashes]): - Hash(es) of the build source, which can be - used to verify that the original source - integrity was maintained in the build. - - The keys to this map are file paths used as - build source and the values contain the hash - values for those files. - - If the build source came in a single package - such as a gzipped tarfile (.tar.gz), the - FileHash will be for the single path to that - file. - context (grafeas.grafeas_v1.types.SourceContext): - If provided, the source code used for the - build came from this location. - additional_contexts (MutableSequence[grafeas.grafeas_v1.types.SourceContext]): - If provided, some of the source code used for - the build may be found in these locations, in - the case where the source repository had - multiple remotes or submodules. This list will - not include the context specified in the context - field. - """ - - artifact_storage_source_uri: str = proto.Field( - proto.STRING, - number=1, - ) - file_hashes: MutableMapping[str, "FileHashes"] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message="FileHashes", - ) - context: "SourceContext" = proto.Field( - proto.MESSAGE, - number=3, - message="SourceContext", - ) - additional_contexts: MutableSequence["SourceContext"] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message="SourceContext", - ) - - -class FileHashes(proto.Message): - r"""Container message for hashes of byte content of files, used - in source messages to verify integrity of source input to the - build. - - Attributes: - file_hash (MutableSequence[grafeas.grafeas_v1.types.Hash]): - Required. Collection of file hashes. - """ - - file_hash: MutableSequence["Hash"] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="Hash", - ) - - -class Hash(proto.Message): - r"""Container message for hash values. - - Attributes: - type_ (str): - Required. The type of hash that was - performed, e.g. "SHA-256". - value (bytes): - Required. The hash value. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - value: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -class Command(proto.Message): - r"""Command describes a step performed as part of the build - pipeline. - - Attributes: - name (str): - Required. Name of the command, as presented on the command - line, or if the command is packaged as a Docker container, - as presented to ``docker pull``. - env (MutableSequence[str]): - Environment variables set before running this - command. - args (MutableSequence[str]): - Command-line arguments used when executing - this command. - dir_ (str): - Working directory (relative to project source - root) used when running this command. - id (str): - Optional unique identifier for this command, used in - wait_for to reference this command as a dependency. - wait_for (MutableSequence[str]): - The ID(s) of the command(s) that this command - depends on. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - env: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - dir_: str = proto.Field( - proto.STRING, - number=4, - ) - id: str = proto.Field( - proto.STRING, - number=5, - ) - wait_for: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - - -class Artifact(proto.Message): - r"""Artifact describes a build product. - - Attributes: - checksum (str): - Hash or checksum value of a binary, or Docker - Registry 2.0 digest of a container. - id (str): - Artifact ID, if any; for container images, this will be a - URL by digest like - ``gcr.io/projectID/imagename@sha256:123456``. - names (MutableSequence[str]): - Related artifact names. This may be the path to a binary or - jar file, or in the case of a container build, the name used - to push the container image to Google Container Registry, as - presented to ``docker push``. Note that a single Artifact ID - can have multiple names, for example if two tags are applied - to one image. - """ - - checksum: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class SourceContext(proto.Message): - r"""A SourceContext is a reference to a tree of files. A - SourceContext together with a path point to a unique revision of - a single file or directory. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - cloud_repo (grafeas.grafeas_v1.types.CloudRepoSourceContext): - A SourceContext referring to a revision in a - Google Cloud Source Repo. - - This field is a member of `oneof`_ ``context``. - gerrit (grafeas.grafeas_v1.types.GerritSourceContext): - A SourceContext referring to a Gerrit - project. - - This field is a member of `oneof`_ ``context``. - git (grafeas.grafeas_v1.types.GitSourceContext): - A SourceContext referring to any third party - Git repo (e.g., GitHub). - - This field is a member of `oneof`_ ``context``. - labels (MutableMapping[str, str]): - Labels with user defined metadata. - """ - - cloud_repo: "CloudRepoSourceContext" = proto.Field( - proto.MESSAGE, - number=1, - oneof="context", - message="CloudRepoSourceContext", - ) - gerrit: "GerritSourceContext" = proto.Field( - proto.MESSAGE, - number=2, - oneof="context", - message="GerritSourceContext", - ) - git: "GitSourceContext" = proto.Field( - proto.MESSAGE, - number=3, - oneof="context", - message="GitSourceContext", - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - - -class AliasContext(proto.Message): - r"""An alias to a repo revision. - - Attributes: - kind (grafeas.grafeas_v1.types.AliasContext.Kind): - The alias kind. - name (str): - The alias name. - """ - - class Kind(proto.Enum): - r"""The type of an alias. - - Values: - KIND_UNSPECIFIED (0): - Unknown. - FIXED (1): - Git tag. - MOVABLE (2): - Git branch. - OTHER (4): - Used to specify non-standard aliases. For - example, if a Git repo has a ref named - "refs/foo/bar". - """ - KIND_UNSPECIFIED = 0 - FIXED = 1 - MOVABLE = 2 - OTHER = 4 - - kind: Kind = proto.Field( - proto.ENUM, - number=1, - enum=Kind, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CloudRepoSourceContext(proto.Message): - r"""A CloudRepoSourceContext denotes a particular revision in a - Google Cloud Source Repo. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - repo_id (grafeas.grafeas_v1.types.RepoId): - The ID of the repo. - revision_id (str): - A revision ID. - - This field is a member of `oneof`_ ``revision``. - alias_context (grafeas.grafeas_v1.types.AliasContext): - An alias, which may be a branch or tag. - - This field is a member of `oneof`_ ``revision``. - """ - - repo_id: "RepoId" = proto.Field( - proto.MESSAGE, - number=1, - message="RepoId", - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - oneof="revision", - ) - alias_context: "AliasContext" = proto.Field( - proto.MESSAGE, - number=3, - oneof="revision", - message="AliasContext", - ) - - -class GerritSourceContext(proto.Message): - r"""A SourceContext referring to a Gerrit project. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - host_uri (str): - The URI of a running Gerrit instance. - gerrit_project (str): - The full project name within the host. - Projects may be nested, so "project/subproject" - is a valid project name. The "repo name" is the - hostURI/project. - revision_id (str): - A revision (commit) ID. - - This field is a member of `oneof`_ ``revision``. - alias_context (grafeas.grafeas_v1.types.AliasContext): - An alias, which may be a branch or tag. - - This field is a member of `oneof`_ ``revision``. - """ - - host_uri: str = proto.Field( - proto.STRING, - number=1, - ) - gerrit_project: str = proto.Field( - proto.STRING, - number=2, - ) - revision_id: str = proto.Field( - proto.STRING, - number=3, - oneof="revision", - ) - alias_context: "AliasContext" = proto.Field( - proto.MESSAGE, - number=4, - oneof="revision", - message="AliasContext", - ) - - -class GitSourceContext(proto.Message): - r"""A GitSourceContext denotes a particular revision in a third - party Git repository (e.g., GitHub). - - Attributes: - url (str): - Git repository URL. - revision_id (str): - Git commit hash. - """ - - url: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class RepoId(proto.Message): - r"""A unique identifier for a Cloud Repo. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - project_repo_id (grafeas.grafeas_v1.types.ProjectRepoId): - A combination of a project ID and a repo - name. - - This field is a member of `oneof`_ ``id``. - uid (str): - A server-assigned, globally unique - identifier. - - This field is a member of `oneof`_ ``id``. - """ - - project_repo_id: "ProjectRepoId" = proto.Field( - proto.MESSAGE, - number=1, - oneof="id", - message="ProjectRepoId", - ) - uid: str = proto.Field( - proto.STRING, - number=2, - oneof="id", - ) - - -class ProjectRepoId(proto.Message): - r"""Selects a repo using a Google Cloud Platform project ID - (e.g., winged-cargo-31) and a repo name within that project. - - Attributes: - project_id (str): - The ID of the project. - repo_name (str): - The name of the repo. Leave empty for the - default repo. - """ - - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - repo_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/sbom.py b/packages/grafeas/grafeas/grafeas_v1/types/sbom.py deleted file mode 100644 index 79bcc14daf6a..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/sbom.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import common, intoto_statement - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "SBOMReferenceNote", - "SBOMReferenceOccurrence", - "SbomReferenceIntotoPayload", - "SbomReferenceIntotoPredicate", - }, -) - - -class SBOMReferenceNote(proto.Message): - r"""The note representing an SBOM reference. - - Attributes: - format_ (str): - The format that SBOM takes. E.g. may be spdx, - cyclonedx, etc... - version (str): - The version of the format that the SBOM - takes. E.g. if the format is spdx, the version - may be 2.3. - """ - - format_: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SBOMReferenceOccurrence(proto.Message): - r"""The occurrence representing an SBOM reference as applied to a - specific resource. The occurrence follows the DSSE - specification. See - https://github.com/secure-systems-lab/dsse/blob/master/envelope.md - for more details. - - Attributes: - payload (grafeas.grafeas_v1.types.SbomReferenceIntotoPayload): - The actual payload that contains the SBOM - reference data. - payload_type (str): - The kind of payload that - SbomReferenceIntotoPayload takes. Since it's in - the intoto format, this value is expected to be - 'application/vnd.in-toto+json'. - signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): - The signatures over the payload. - """ - - payload: "SbomReferenceIntotoPayload" = proto.Field( - proto.MESSAGE, - number=1, - message="SbomReferenceIntotoPayload", - ) - payload_type: str = proto.Field( - proto.STRING, - number=2, - ) - signatures: MutableSequence[common.EnvelopeSignature] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=common.EnvelopeSignature, - ) - - -class SbomReferenceIntotoPayload(proto.Message): - r"""The actual payload that contains the SBOM Reference data. - The payload follows the intoto statement specification. See - https://github.com/in-toto/attestation/blob/main/spec/v1.0/statement.md - for more details. - - Attributes: - type_ (str): - Identifier for the schema of the Statement. - predicate_type (str): - URI identifying the type of the Predicate. - subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): - Set of software artifacts that the - attestation applies to. Each element represents - a single software artifact. - predicate (grafeas.grafeas_v1.types.SbomReferenceIntotoPredicate): - Additional parameters of the Predicate. - Includes the actual data about the SBOM. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - predicate_type: str = proto.Field( - proto.STRING, - number=2, - ) - subject: MutableSequence[intoto_statement.Subject] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=intoto_statement.Subject, - ) - predicate: "SbomReferenceIntotoPredicate" = proto.Field( - proto.MESSAGE, - number=4, - message="SbomReferenceIntotoPredicate", - ) - - -class SbomReferenceIntotoPredicate(proto.Message): - r"""A predicate which describes the SBOM being referenced. - - Attributes: - referrer_id (str): - The person or system referring this predicate - to the consumer. - location (str): - The location of the SBOM. - mime_type (str): - The mime type of the SBOM. - digest (MutableMapping[str, str]): - A map of algorithm to digest of the contents - of the SBOM. - """ - - referrer_id: str = proto.Field( - proto.STRING, - number=1, - ) - location: str = proto.Field( - proto.STRING, - number=2, - ) - mime_type: str = proto.Field( - proto.STRING, - number=3, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/secret.py b/packages/grafeas/grafeas/grafeas_v1/types/secret.py deleted file mode 100644 index e36597dd1430..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/secret.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import common - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "SecretKind", - "SecretNote", - "SecretOccurrence", - "SecretLocation", - "SecretStatus", - }, -) - - -class SecretKind(proto.Enum): - r"""Kind of secret. - - Values: - SECRET_KIND_UNSPECIFIED (0): - Unspecified - SECRET_KIND_UNKNOWN (1): - The secret kind is unknown. - SECRET_KIND_GCP_SERVICE_ACCOUNT_KEY (2): - A GCP service account key per: - - https://cloud.google.com/iam/docs/creating-managing-service-account-keys - """ - SECRET_KIND_UNSPECIFIED = 0 - SECRET_KIND_UNKNOWN = 1 - SECRET_KIND_GCP_SERVICE_ACCOUNT_KEY = 2 - - -class SecretNote(proto.Message): - r"""The note representing a secret.""" - - -class SecretOccurrence(proto.Message): - r"""The occurrence provides details of a secret. - - Attributes: - kind (grafeas.grafeas_v1.types.SecretKind): - Type of secret. - locations (MutableSequence[grafeas.grafeas_v1.types.SecretLocation]): - Locations where the secret is detected. - statuses (MutableSequence[grafeas.grafeas_v1.types.SecretStatus]): - Status of the secret. - """ - - kind: "SecretKind" = proto.Field( - proto.ENUM, - number=1, - enum="SecretKind", - ) - locations: MutableSequence["SecretLocation"] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message="SecretLocation", - ) - statuses: MutableSequence["SecretStatus"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="SecretStatus", - ) - - -class SecretLocation(proto.Message): - r"""The location of the secret. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - file_location (grafeas.grafeas_v1.types.FileLocation): - The secret is found from a file. - - This field is a member of `oneof`_ ``location``. - """ - - file_location: common.FileLocation = proto.Field( - proto.MESSAGE, - number=1, - oneof="location", - message=common.FileLocation, - ) - - -class SecretStatus(proto.Message): - r"""The status of the secret with a timestamp. - - Attributes: - status (grafeas.grafeas_v1.types.SecretStatus.Status): - The status of the secret. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time the secret status was last updated. - message (str): - Optional message about the status code. - """ - - class Status(proto.Enum): - r"""The status of the secret. - - Values: - STATUS_UNSPECIFIED (0): - Unspecified - UNKNOWN (1): - The status of the secret is unknown. - VALID (2): - The secret is valid. - INVALID (3): - The secret is invalid. - """ - STATUS_UNSPECIFIED = 0 - UNKNOWN = 1 - VALID = 2 - INVALID = 3 - - status: Status = proto.Field( - proto.ENUM, - number=1, - enum=Status, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - message: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/severity.py b/packages/grafeas/grafeas/grafeas_v1/types/severity.py deleted file mode 100644 index af2b165d5678..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/severity.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "Severity", - }, -) - - -class Severity(proto.Enum): - r"""Note provider assigned severity/impact ranking. - - Values: - SEVERITY_UNSPECIFIED (0): - Unknown. - MINIMAL (1): - Minimal severity. - LOW (2): - Low severity. - MEDIUM (3): - Medium severity. - HIGH (4): - High severity. - CRITICAL (5): - Critical severity. - """ - SEVERITY_UNSPECIFIED = 0 - MINIMAL = 1 - LOW = 2 - MEDIUM = 3 - HIGH = 4 - CRITICAL = 5 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py b/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py deleted file mode 100644 index 0640bae93566..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "SlsaProvenance", - }, -) - - -class SlsaProvenance(proto.Message): - r""" - - Attributes: - builder (grafeas.grafeas_v1.types.SlsaProvenance.SlsaBuilder): - required - recipe (grafeas.grafeas_v1.types.SlsaProvenance.SlsaRecipe): - Identifies the configuration used for the - build. When combined with materials, this SHOULD - fully describe the build, such that re-running - this recipe results in bit-for-bit identical - output (if the build is reproducible). - metadata (grafeas.grafeas_v1.types.SlsaProvenance.SlsaMetadata): - - materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenance.Material]): - The collection of artifacts that influenced - the build including sources, dependencies, build - tools, base images, and so on. This is - considered to be incomplete unless - metadata.completeness.materials is true. Unset - or null is equivalent to empty. - """ - - class SlsaRecipe(proto.Message): - r"""Steps taken to build the artifact. - For a TaskRun, typically each container corresponds to one step - in the recipe. - - Attributes: - type_ (str): - URI indicating what type of recipe was - performed. It determines the meaning of - recipe.entryPoint, recipe.arguments, - recipe.environment, and materials. - defined_in_material (int): - Index in materials containing the recipe - steps that are not implied by recipe.type. For - example, if the recipe type were "make", then - this would point to the source containing the - Makefile, not the make program itself. Set to -1 - if the recipe doesn't come from a material, as - zero is default unset value for int64. - entry_point (str): - String identifying the entry point into the - build. This is often a path to a configuration - file and/or a target label within that file. The - syntax and meaning are defined by recipe.type. - For example, if the recipe type were "make", - then this would reference the directory in which - to run make as well as which target to use. - arguments (google.protobuf.any_pb2.Any): - Collection of all external inputs that - influenced the build on top of - recipe.definedInMaterial and recipe.entryPoint. - For example, if the recipe type were "make", - then this might be the flags passed to make - aside from the target, which is captured in - recipe.entryPoint. Depending on the recipe Type, - the structure may be different. - environment (google.protobuf.any_pb2.Any): - Any other builder-controlled inputs necessary - for correctly evaluating the recipe. Usually - only needed for reproducing the build but not - evaluated as part of policy. Depending on the - recipe Type, the structure may be different. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - defined_in_material: int = proto.Field( - proto.INT64, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - arguments: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=4, - message=any_pb2.Any, - ) - environment: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=5, - message=any_pb2.Any, - ) - - class SlsaCompleteness(proto.Message): - r"""Indicates that the builder claims certain fields in this - message to be complete. - - Attributes: - arguments (bool): - If true, the builder claims that - recipe.arguments is complete, meaning that all - external inputs are properly captured in the - recipe. - environment (bool): - If true, the builder claims that - recipe.environment is claimed to be complete. - materials (bool): - If true, the builder claims that materials - are complete, usually through some controls to - prevent network access. Sometimes called - "hermetic". - """ - - arguments: bool = proto.Field( - proto.BOOL, - number=1, - ) - environment: bool = proto.Field( - proto.BOOL, - number=2, - ) - materials: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SlsaMetadata(proto.Message): - r"""Other properties of the build. - - Attributes: - build_invocation_id (str): - Identifies the particular build invocation, - which can be useful for finding associated logs - or other ad-hoc analysis. The value SHOULD be - globally unique, per in-toto Provenance spec. - build_started_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build started. - build_finished_on (google.protobuf.timestamp_pb2.Timestamp): - The timestamp of when the build completed. - completeness (grafeas.grafeas_v1.types.SlsaProvenance.SlsaCompleteness): - Indicates that the builder claims certain - fields in this message to be complete. - reproducible (bool): - If true, the builder claims that running the - recipe on materials will produce bit-for-bit - identical output. - """ - - build_invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - build_started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - build_finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - completeness: "SlsaProvenance.SlsaCompleteness" = proto.Field( - proto.MESSAGE, - number=4, - message="SlsaProvenance.SlsaCompleteness", - ) - reproducible: bool = proto.Field( - proto.BOOL, - number=5, - ) - - class SlsaBuilder(proto.Message): - r""" - - Attributes: - id (str): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class Material(proto.Message): - r""" - - Attributes: - uri (str): - - digest (MutableMapping[str, str]): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - builder: SlsaBuilder = proto.Field( - proto.MESSAGE, - number=1, - message=SlsaBuilder, - ) - recipe: SlsaRecipe = proto.Field( - proto.MESSAGE, - number=2, - message=SlsaRecipe, - ) - metadata: SlsaMetadata = proto.Field( - proto.MESSAGE, - number=3, - message=SlsaMetadata, - ) - materials: MutableSequence[Material] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Material, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py b/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py deleted file mode 100644 index 590263762adf..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py +++ /dev/null @@ -1,240 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "SlsaProvenanceZeroTwo", - }, -) - - -class SlsaProvenanceZeroTwo(proto.Message): - r"""See full explanation of fields at slsa.dev/provenance/v0.2. - - Attributes: - builder (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaBuilder): - - build_type (str): - - invocation (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaInvocation): - - build_config (google.protobuf.struct_pb2.Struct): - - metadata (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMetadata): - - materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMaterial]): - - """ - - class SlsaBuilder(proto.Message): - r"""Identifies the entity that executed the recipe, which is - trusted to have correctly performed the operation and populated - this provenance. - - Attributes: - id (str): - - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class SlsaMaterial(proto.Message): - r"""The collection of artifacts that influenced the build - including sources, dependencies, build tools, base images, and - so on. - - Attributes: - uri (str): - - digest (MutableMapping[str, str]): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - class SlsaInvocation(proto.Message): - r"""Identifies the event that kicked off the build. - - Attributes: - config_source (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaConfigSource): - - parameters (google.protobuf.struct_pb2.Struct): - - environment (google.protobuf.struct_pb2.Struct): - - """ - - config_source: "SlsaProvenanceZeroTwo.SlsaConfigSource" = proto.Field( - proto.MESSAGE, - number=1, - message="SlsaProvenanceZeroTwo.SlsaConfigSource", - ) - parameters: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - environment: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - class SlsaConfigSource(proto.Message): - r"""Describes where the config file that kicked off the build - came from. This is effectively a pointer to the source where - buildConfig came from. - - Attributes: - uri (str): - - digest (MutableMapping[str, str]): - - entry_point (str): - - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - digest: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - - class SlsaMetadata(proto.Message): - r"""Other properties of the build. - - Attributes: - build_invocation_id (str): - - build_started_on (google.protobuf.timestamp_pb2.Timestamp): - - build_finished_on (google.protobuf.timestamp_pb2.Timestamp): - - completeness (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaCompleteness): - - reproducible (bool): - - """ - - build_invocation_id: str = proto.Field( - proto.STRING, - number=1, - ) - build_started_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - build_finished_on: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - completeness: "SlsaProvenanceZeroTwo.SlsaCompleteness" = proto.Field( - proto.MESSAGE, - number=4, - message="SlsaProvenanceZeroTwo.SlsaCompleteness", - ) - reproducible: bool = proto.Field( - proto.BOOL, - number=5, - ) - - class SlsaCompleteness(proto.Message): - r"""Indicates that the builder claims certain fields in this - message to be complete. - - Attributes: - parameters (bool): - - environment (bool): - - materials (bool): - - """ - - parameters: bool = proto.Field( - proto.BOOL, - number=1, - ) - environment: bool = proto.Field( - proto.BOOL, - number=2, - ) - materials: bool = proto.Field( - proto.BOOL, - number=3, - ) - - builder: SlsaBuilder = proto.Field( - proto.MESSAGE, - number=1, - message=SlsaBuilder, - ) - build_type: str = proto.Field( - proto.STRING, - number=2, - ) - invocation: SlsaInvocation = proto.Field( - proto.MESSAGE, - number=3, - message=SlsaInvocation, - ) - build_config: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - metadata: SlsaMetadata = proto.Field( - proto.MESSAGE, - number=5, - message=SlsaMetadata, - ) - materials: MutableSequence[SlsaMaterial] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=SlsaMaterial, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/upgrade.py b/packages/grafeas/grafeas/grafeas_v1/types/upgrade.py deleted file mode 100644 index 9621aa1f85d7..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/upgrade.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import package as g_package - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "UpgradeNote", - "UpgradeDistribution", - "WindowsUpdate", - "UpgradeOccurrence", - }, -) - - -class UpgradeNote(proto.Message): - r"""An Upgrade Note represents a potential upgrade of a package to a - given version. For each package version combination (i.e. bash 4.0, - bash 4.1, bash 4.1.2), there will be an Upgrade Note. For Windows, - windows_update field represents the information related to the - update. - - Attributes: - package (str): - Required for non-Windows OS. The package this - Upgrade is for. - version (grafeas.grafeas_v1.types.Version): - Required for non-Windows OS. The version of - the package in machine + human readable form. - distributions (MutableSequence[grafeas.grafeas_v1.types.UpgradeDistribution]): - Metadata about the upgrade for each specific - operating system. - windows_update (grafeas.grafeas_v1.types.WindowsUpdate): - Required for Windows OS. Represents the - metadata about the Windows update. - """ - - package: str = proto.Field( - proto.STRING, - number=1, - ) - version: g_package.Version = proto.Field( - proto.MESSAGE, - number=2, - message=g_package.Version, - ) - distributions: MutableSequence["UpgradeDistribution"] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message="UpgradeDistribution", - ) - windows_update: "WindowsUpdate" = proto.Field( - proto.MESSAGE, - number=4, - message="WindowsUpdate", - ) - - -class UpgradeDistribution(proto.Message): - r"""The Upgrade Distribution represents metadata about the - Upgrade for each operating system (CPE). Some distributions have - additional metadata around updates, classifying them into - various categories and severities. - - Attributes: - cpe_uri (str): - Required - The specific operating system this - metadata applies to. See - https://cpe.mitre.org/specification/. - classification (str): - The operating system classification of this Upgrade, as - specified by the upstream operating system upgrade feed. For - Windows the classification is one of the category_ids listed - at - https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ff357803(v=vs.85) - severity (str): - The severity as specified by the upstream - operating system. - cve (MutableSequence[str]): - The cve tied to this Upgrade. - """ - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - classification: str = proto.Field( - proto.STRING, - number=2, - ) - severity: str = proto.Field( - proto.STRING, - number=3, - ) - cve: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class WindowsUpdate(proto.Message): - r"""Windows Update represents the metadata about the update for - the Windows operating system. The fields in this message come - from the Windows Update API documented at - https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdate. - - Attributes: - identity (grafeas.grafeas_v1.types.WindowsUpdate.Identity): - Required - The unique identifier for the - update. - title (str): - The localized title of the update. - description (str): - The localized description of the update. - categories (MutableSequence[grafeas.grafeas_v1.types.WindowsUpdate.Category]): - The list of categories to which the update - belongs. - kb_article_ids (MutableSequence[str]): - The Microsoft Knowledge Base article IDs that - are associated with the update. - support_url (str): - The hyperlink to the support information for - the update. - last_published_timestamp (google.protobuf.timestamp_pb2.Timestamp): - The last published timestamp of the update. - """ - - class Identity(proto.Message): - r"""The unique identifier of the update. - - Attributes: - update_id (str): - The revision independent identifier of the - update. - revision (int): - The revision number of the update. - """ - - update_id: str = proto.Field( - proto.STRING, - number=1, - ) - revision: int = proto.Field( - proto.INT32, - number=2, - ) - - class Category(proto.Message): - r"""The category to which the update belongs. - - Attributes: - category_id (str): - The identifier of the category. - name (str): - The localized name of the category. - """ - - category_id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - identity: Identity = proto.Field( - proto.MESSAGE, - number=1, - message=Identity, - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - categories: MutableSequence[Category] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Category, - ) - kb_article_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - support_url: str = proto.Field( - proto.STRING, - number=6, - ) - last_published_timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - -class UpgradeOccurrence(proto.Message): - r"""An Upgrade Occurrence represents that a specific resource_url could - install a specific upgrade. This presence is supplied via local - sources (i.e. it is present in the mirror and the running system has - noticed its availability). For Windows, both distribution and - windows_update contain information for the Windows update. - - Attributes: - package (str): - Required for non-Windows OS. The package this - Upgrade is for. - parsed_version (grafeas.grafeas_v1.types.Version): - Required for non-Windows OS. The version of - the package in a machine + human readable form. - distribution (grafeas.grafeas_v1.types.UpgradeDistribution): - Metadata about the upgrade for available for the specific - operating system for the resource_url. This allows efficient - filtering, as well as making it easier to use the - occurrence. - windows_update (grafeas.grafeas_v1.types.WindowsUpdate): - Required for Windows OS. Represents the - metadata about the Windows update. - """ - - package: str = proto.Field( - proto.STRING, - number=1, - ) - parsed_version: g_package.Version = proto.Field( - proto.MESSAGE, - number=3, - message=g_package.Version, - ) - distribution: "UpgradeDistribution" = proto.Field( - proto.MESSAGE, - number=4, - message="UpgradeDistribution", - ) - windows_update: "WindowsUpdate" = proto.Field( - proto.MESSAGE, - number=5, - message="WindowsUpdate", - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/vex.py b/packages/grafeas/grafeas/grafeas_v1/types/vex.py deleted file mode 100644 index a0a0666736ee..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/vex.py +++ /dev/null @@ -1,390 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from grafeas.grafeas_v1.types import common - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "VulnerabilityAssessmentNote", - }, -) - - -class VulnerabilityAssessmentNote(proto.Message): - r"""A single VulnerabilityAssessmentNote represents - one particular product's vulnerability assessment for one CVE. - - Attributes: - title (str): - The title of the note. E.g. ``Vex-Debian-11.4`` - short_description (str): - A one sentence description of this Vex. - long_description (str): - A detailed description of this Vex. - language_code (str): - Identifies the language used by this - document, corresponding to IETF BCP 47 / RFC - 5646. - publisher (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Publisher): - Publisher details of this Note. - product (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Product): - The product affected by this vex. - assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment): - Represents a vulnerability assessment for the - product. - """ - - class Publisher(proto.Message): - r"""Publisher contains information about the publisher of - this Note. - (-- api-linter: core::0123::resource-annotation=disabled - aip.dev/not-precedent: Publisher is not a separate resource. --) - - Attributes: - name (str): - Name of the publisher. - Examples: 'Google', 'Google Cloud Platform'. - issuing_authority (str): - Provides information about the authority of - the issuing party to release the document, in - particular, the party's constituency and - responsibilities or other obligations. - publisher_namespace (str): - The context or namespace. - Contains a URL which is under control of the - issuing party and can be used as a globally - unique identifier for that issuing party. - Example: https://csaf.io - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - issuing_authority: str = proto.Field( - proto.STRING, - number=2, - ) - publisher_namespace: str = proto.Field( - proto.STRING, - number=3, - ) - - class Product(proto.Message): - r"""Product contains information about a product and how to - uniquely identify it. - (-- api-linter: core::0123::resource-annotation=disabled - aip.dev/not-precedent: Product is not a separate resource. --) - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Name of the product. - id (str): - Token that identifies a product so that it - can be referred to from other parts in the - document. There is no predefined format as long - as it uniquely identifies a group in the context - of the current document. - generic_uri (str): - Contains a URI which is vendor-specific. - Example: The artifact repository URL of an - image. - - This field is a member of `oneof`_ ``identifier``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - generic_uri: str = proto.Field( - proto.STRING, - number=3, - oneof="identifier", - ) - - class Assessment(proto.Message): - r"""Assessment provides all information that is related to a - single vulnerability for this product. - - Attributes: - cve (str): - Holds the MITRE standard Common Vulnerabilities and - Exposures (CVE) tracking number for the vulnerability. - Deprecated: Use vulnerability_id instead to denote CVEs. - vulnerability_id (str): - The vulnerability identifier for this - Assessment. Will hold one of common identifiers - e.g. CVE, GHSA etc. - short_description (str): - A one sentence description of this Vex. - long_description (str): - A detailed description of this Vex. - related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - Holds a list of references associated with - this vulnerability item and assessment. These - uris have additional information about the - vulnerability and the assessment itself. E.g. - Link to a document which details how this - assessment concluded the state of this - vulnerability. - state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): - Provides the state of this Vulnerability - assessment. - impacts (MutableSequence[str]): - Contains information about the impact of this - vulnerability, this will change with time. - justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): - Justification provides the justification when the state of - the assessment if NOT_AFFECTED. - remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): - Specifies details on how to handle (and - presumably, fix) a vulnerability. - """ - - class State(proto.Enum): - r"""Provides the state of this Vulnerability assessment. - - Values: - STATE_UNSPECIFIED (0): - No state is specified. - AFFECTED (1): - This product is known to be affected by this - vulnerability. - NOT_AFFECTED (2): - This product is known to be not affected by - this vulnerability. - FIXED (3): - This product contains a fix for this - vulnerability. - UNDER_INVESTIGATION (4): - It is not known yet whether these versions - are or are not affected by the vulnerability. - However, it is still under investigation. - """ - STATE_UNSPECIFIED = 0 - AFFECTED = 1 - NOT_AFFECTED = 2 - FIXED = 3 - UNDER_INVESTIGATION = 4 - - class Justification(proto.Message): - r"""Justification provides the justification when the state of the - assessment if NOT_AFFECTED. - - Attributes: - justification_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification.JustificationType): - The justification type for this - vulnerability. - details (str): - Additional details on why this justification - was chosen. - """ - - class JustificationType(proto.Enum): - r"""Provides the type of justification. - - Values: - JUSTIFICATION_TYPE_UNSPECIFIED (0): - JUSTIFICATION_TYPE_UNSPECIFIED. - COMPONENT_NOT_PRESENT (1): - The vulnerable component is not present in - the product. - VULNERABLE_CODE_NOT_PRESENT (2): - The vulnerable code is not present. Typically - this case occurs when source code is configured - or built in a way that excludes the vulnerable - code. - VULNERABLE_CODE_NOT_IN_EXECUTE_PATH (3): - The vulnerable code can not be executed. - Typically this case occurs when the product - includes the vulnerable code but does not call - or use the vulnerable code. - VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY (4): - The vulnerable code cannot be controlled by - an attacker to exploit the vulnerability. - INLINE_MITIGATIONS_ALREADY_EXIST (5): - The product includes built-in protections or - features that prevent exploitation of the - vulnerability. These built-in protections cannot - be subverted by the attacker and cannot be - configured or disabled by the user. These - mitigations completely prevent exploitation - based on known attack vectors. - """ - JUSTIFICATION_TYPE_UNSPECIFIED = 0 - COMPONENT_NOT_PRESENT = 1 - VULNERABLE_CODE_NOT_PRESENT = 2 - VULNERABLE_CODE_NOT_IN_EXECUTE_PATH = 3 - VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY = 4 - INLINE_MITIGATIONS_ALREADY_EXIST = 5 - - justification_type: "VulnerabilityAssessmentNote.Assessment.Justification.JustificationType" = proto.Field( - proto.ENUM, - number=1, - enum="VulnerabilityAssessmentNote.Assessment.Justification.JustificationType", - ) - details: str = proto.Field( - proto.STRING, - number=2, - ) - - class Remediation(proto.Message): - r"""Specifies details on how to handle (and presumably, fix) a - vulnerability. - - Attributes: - remediation_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType): - The type of remediation that can be applied. - details (str): - Contains a comprehensive human-readable - discussion of the remediation. - remediation_uri (grafeas.grafeas_v1.types.RelatedUrl): - Contains the URL where to obtain the - remediation. - """ - - class RemediationType(proto.Enum): - r"""The type of remediation that can be applied. - - Values: - REMEDIATION_TYPE_UNSPECIFIED (0): - No remediation type specified. - MITIGATION (1): - A MITIGATION is available. - NO_FIX_PLANNED (2): - No fix is planned. - NONE_AVAILABLE (3): - Not available. - VENDOR_FIX (4): - A vendor fix is available. - WORKAROUND (5): - A workaround is available. - """ - REMEDIATION_TYPE_UNSPECIFIED = 0 - MITIGATION = 1 - NO_FIX_PLANNED = 2 - NONE_AVAILABLE = 3 - VENDOR_FIX = 4 - WORKAROUND = 5 - - remediation_type: "VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType" = proto.Field( - proto.ENUM, - number=1, - enum="VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType", - ) - details: str = proto.Field( - proto.STRING, - number=2, - ) - remediation_uri: common.RelatedUrl = proto.Field( - proto.MESSAGE, - number=3, - message=common.RelatedUrl, - ) - - cve: str = proto.Field( - proto.STRING, - number=1, - ) - vulnerability_id: str = proto.Field( - proto.STRING, - number=9, - ) - short_description: str = proto.Field( - proto.STRING, - number=2, - ) - long_description: str = proto.Field( - proto.STRING, - number=3, - ) - related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=common.RelatedUrl, - ) - state: "VulnerabilityAssessmentNote.Assessment.State" = proto.Field( - proto.ENUM, - number=5, - enum="VulnerabilityAssessmentNote.Assessment.State", - ) - impacts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - justification: "VulnerabilityAssessmentNote.Assessment.Justification" = ( - proto.Field( - proto.MESSAGE, - number=7, - message="VulnerabilityAssessmentNote.Assessment.Justification", - ) - ) - remediations: MutableSequence[ - "VulnerabilityAssessmentNote.Assessment.Remediation" - ] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message="VulnerabilityAssessmentNote.Assessment.Remediation", - ) - - title: str = proto.Field( - proto.STRING, - number=1, - ) - short_description: str = proto.Field( - proto.STRING, - number=2, - ) - long_description: str = proto.Field( - proto.STRING, - number=3, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - publisher: Publisher = proto.Field( - proto.MESSAGE, - number=5, - message=Publisher, - ) - product: Product = proto.Field( - proto.MESSAGE, - number=6, - message=Product, - ) - assessment: Assessment = proto.Field( - proto.MESSAGE, - number=7, - message=Assessment, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py b/packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py deleted file mode 100644 index 42da348e7a7d..000000000000 --- a/packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py +++ /dev/null @@ -1,597 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 annotations - -from typing import MutableMapping, MutableSequence - -from google.protobuf import timestamp_pb2 # type: ignore -import proto # type: ignore - -from grafeas.grafeas_v1.types import common, cvss, package -from grafeas.grafeas_v1.types import severity as g_severity -from grafeas.grafeas_v1.types import vex - -__protobuf__ = proto.module( - package="grafeas.v1", - manifest={ - "VulnerabilityNote", - "VulnerabilityOccurrence", - }, -) - - -class VulnerabilityNote(proto.Message): - r"""A security vulnerability that can be found in resources. - - Attributes: - cvss_score (float): - The CVSS score of this vulnerability. CVSS - score is on a scale of 0 - 10 where 0 indicates - low severity and 10 indicates high severity. - severity (grafeas.grafeas_v1.types.Severity): - The note provider assigned severity of this - vulnerability. - details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.Detail]): - Details of all known distros and packages - affected by this vulnerability. - cvss_v3 (grafeas.grafeas_v1.types.CVSSv3): - The full description of the CVSSv3 for this - vulnerability. - windows_details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail]): - Windows details get their own format because - the information format and model don't match a - normal detail. Specifically Windows updates are - done as patches, thus Windows vulnerabilities - really are a missing package, rather than a - package being at an incorrect version. - source_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time this information was last changed at - the source. This is an upstream timestamp from - the underlying information source - e.g. Ubuntu - security tracker. - cvss_version (grafeas.grafeas_v1.types.CVSSVersion): - CVSS version used to populate cvss_score and severity. - cvss_v2 (grafeas.grafeas_v1.types.CVSS): - The full description of the v2 CVSS for this - vulnerability. - """ - - class Detail(proto.Message): - r"""A detail for a distro and package affected by this - vulnerability and its associated fix (if one is available). - - Attributes: - severity_name (str): - The distro assigned severity of this - vulnerability. - description (str): - A vendor-specific description of this - vulnerability. - package_type (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - affected_cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability affects. - affected_package (str): - Required. The package this vulnerability - affects. - affected_version_start (grafeas.grafeas_v1.types.Version): - The version number at the start of an interval in which this - vulnerability exists. A vulnerability can affect a package - between version numbers that are disjoint sets of intervals - (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) - each of which will be represented in its own Detail. If a - specific affected version is provided by a vulnerability - database, affected_version_start and affected_version_end - will be the same in that Detail. - affected_version_end (grafeas.grafeas_v1.types.Version): - The version number at the end of an interval in which this - vulnerability exists. A vulnerability can affect a package - between version numbers that are disjoint sets of intervals - (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) - each of which will be represented in its own Detail. If a - specific affected version is provided by a vulnerability - database, affected_version_start and affected_version_end - will be the same in that Detail. - fixed_cpe_uri (str): - The distro recommended `CPE - URI `__ to update to - that contains a fix for this vulnerability. It is possible - for this to be different from the affected_cpe_uri. - fixed_package (str): - The distro recommended package to update to that contains a - fix for this vulnerability. It is possible for this to be - different from the affected_package. - fixed_version (grafeas.grafeas_v1.types.Version): - The distro recommended version to update to - that contains a fix for this vulnerability. - Setting this to VersionKind.MAXIMUM means no - such version is yet available. - is_obsolete (bool): - Whether this detail is obsolete. Occurrences - are expected not to point to obsolete details. - source_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time this information was last changed at - the source. This is an upstream timestamp from - the underlying information source - e.g. Ubuntu - security tracker. - source (str): - The source from which the information in this - Detail was obtained. - vendor (str): - The name of the vendor of the product. - """ - - severity_name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - affected_cpe_uri: str = proto.Field( - proto.STRING, - number=4, - ) - affected_package: str = proto.Field( - proto.STRING, - number=5, - ) - affected_version_start: package.Version = proto.Field( - proto.MESSAGE, - number=6, - message=package.Version, - ) - affected_version_end: package.Version = proto.Field( - proto.MESSAGE, - number=7, - message=package.Version, - ) - fixed_cpe_uri: str = proto.Field( - proto.STRING, - number=8, - ) - fixed_package: str = proto.Field( - proto.STRING, - number=9, - ) - fixed_version: package.Version = proto.Field( - proto.MESSAGE, - number=10, - message=package.Version, - ) - is_obsolete: bool = proto.Field( - proto.BOOL, - number=11, - ) - source_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - source: str = proto.Field( - proto.STRING, - number=13, - ) - vendor: str = proto.Field( - proto.STRING, - number=14, - ) - - class WindowsDetail(proto.Message): - r""" - - Attributes: - cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability affects. - name (str): - Required. The name of this vulnerability. - description (str): - The description of this vulnerability. - fixing_kbs (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail.KnowledgeBase]): - Required. The names of the KBs which have - hotfixes to mitigate this vulnerability. Note - that there may be multiple hotfixes (and thus - multiple KBs) that mitigate a given - vulnerability. Currently any listed KBs presence - is considered a fix. - """ - - class KnowledgeBase(proto.Message): - r""" - - Attributes: - name (str): - The KB name (generally of the form KB[0-9]+ (e.g., - KB123456)). - url (str): - A link to the KB in the [Windows update catalog] - (https://www.catalog.update.microsoft.com/). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - url: str = proto.Field( - proto.STRING, - number=2, - ) - - cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - fixing_kbs: MutableSequence[ - "VulnerabilityNote.WindowsDetail.KnowledgeBase" - ] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message="VulnerabilityNote.WindowsDetail.KnowledgeBase", - ) - - cvss_score: float = proto.Field( - proto.FLOAT, - number=1, - ) - severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=2, - enum=g_severity.Severity, - ) - details: MutableSequence[Detail] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Detail, - ) - cvss_v3: cvss.CVSSv3 = proto.Field( - proto.MESSAGE, - number=4, - message=cvss.CVSSv3, - ) - windows_details: MutableSequence[WindowsDetail] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=WindowsDetail, - ) - source_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - cvss_version: cvss.CVSSVersion = proto.Field( - proto.ENUM, - number=7, - enum=cvss.CVSSVersion, - ) - cvss_v2: cvss.CVSS = proto.Field( - proto.MESSAGE, - number=8, - message=cvss.CVSS, - ) - - -class VulnerabilityOccurrence(proto.Message): - r"""An occurrence of a severity vulnerability on a resource. - - Attributes: - type_ (str): - The type of package; whether native or non - native (e.g., ruby gems, node.js packages, - etc.). - severity (grafeas.grafeas_v1.types.Severity): - Output only. The note provider assigned - severity of this vulnerability. - cvss_score (float): - Output only. The CVSS score of this - vulnerability. CVSS score is on a scale of 0 - - 10 where 0 indicates low severity and 10 - indicates high severity. - cvssv3 (grafeas.grafeas_v1.types.CVSS): - The cvss v3 score for the vulnerability. - package_issue (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityOccurrence.PackageIssue]): - Required. The set of affected locations and - their fixes (if available) within the associated - resource. - short_description (str): - Output only. A one sentence description of - this vulnerability. - long_description (str): - Output only. A detailed description of this - vulnerability. - related_urls (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - Output only. URLs related to this - vulnerability. - effective_severity (grafeas.grafeas_v1.types.Severity): - The distro assigned severity for this - vulnerability when it is available, otherwise - this is the note provider assigned severity. - - When there are multiple PackageIssues for this - vulnerability, they can have different effective - severities because some might be provided by the - distro while others are provided by the language - ecosystem for a language pack. For this reason, - it is advised to use the effective severity on - the PackageIssue level. In the case where - multiple PackageIssues have differing effective - severities, this field should be the highest - severity for any of the PackageIssues. - fix_available (bool): - Output only. Whether at least one of the - affected packages has a fix available. - cvss_version (grafeas.grafeas_v1.types.CVSSVersion): - Output only. CVSS version used to populate cvss_score and - severity. - cvss_v2 (grafeas.grafeas_v1.types.CVSS): - The cvss v2 score for the vulnerability. - vex_assessment (grafeas.grafeas_v1.types.VulnerabilityOccurrence.VexAssessment): - - extra_details (str): - Occurrence-specific extra details about the - vulnerability. - """ - - class PackageIssue(proto.Message): - r"""A detail for a distro and package this vulnerability - occurrence was found in and its associated fix (if one is - available). - - Attributes: - affected_cpe_uri (str): - Required. The `CPE - URI `__ this - vulnerability was found in. - affected_package (str): - Required. The package this vulnerability was - found in. - affected_version (grafeas.grafeas_v1.types.Version): - Required. The version of the package that is - installed on the resource affected by this - vulnerability. - fixed_cpe_uri (str): - The `CPE URI `__ this - vulnerability was fixed in. It is possible for this to be - different from the affected_cpe_uri. - fixed_package (str): - The package this vulnerability was fixed in. It is possible - for this to be different from the affected_package. - fixed_version (grafeas.grafeas_v1.types.Version): - Required. The version of the package this - vulnerability was fixed in. Setting this to - VersionKind.MAXIMUM means no fix is yet - available. - fix_available (bool): - Output only. Whether a fix is available for - this package. - package_type (str): - The type of package (e.g. OS, MAVEN, GO). - effective_severity (grafeas.grafeas_v1.types.Severity): - The distro or language system assigned - severity for this vulnerability when that is - available and note provider assigned severity - when it is not available. - file_location (MutableSequence[grafeas.grafeas_v1.types.FileLocation]): - The location at which this package was found. - """ - - affected_cpe_uri: str = proto.Field( - proto.STRING, - number=1, - ) - affected_package: str = proto.Field( - proto.STRING, - number=2, - ) - affected_version: package.Version = proto.Field( - proto.MESSAGE, - number=3, - message=package.Version, - ) - fixed_cpe_uri: str = proto.Field( - proto.STRING, - number=4, - ) - fixed_package: str = proto.Field( - proto.STRING, - number=5, - ) - fixed_version: package.Version = proto.Field( - proto.MESSAGE, - number=6, - message=package.Version, - ) - fix_available: bool = proto.Field( - proto.BOOL, - number=7, - ) - package_type: str = proto.Field( - proto.STRING, - number=8, - ) - effective_severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=9, - enum=g_severity.Severity, - ) - file_location: MutableSequence[common.FileLocation] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=common.FileLocation, - ) - - class VexAssessment(proto.Message): - r"""VexAssessment provides all publisher provided Vex information - that is related to this vulnerability. - - Attributes: - cve (str): - Holds the MITRE standard Common Vulnerabilities and - Exposures (CVE) tracking number for the vulnerability. - Deprecated: Use vulnerability_id instead to denote CVEs. - vulnerability_id (str): - The vulnerability identifier for this - Assessment. Will hold one of common identifiers - e.g. CVE, GHSA etc. - related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): - Holds a list of references associated with - this vulnerability item and assessment. - note_name (str): - The VulnerabilityAssessment note from which this - VexAssessment was generated. This will be of the form: - ``projects/[PROJECT_ID]/notes/[NOTE_ID]``. (-- api-linter: - core::0122::name-suffix=disabled aip.dev/not-precedent: The - suffix is kept for consistency. --) - state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): - Provides the state of this Vulnerability - assessment. - impacts (MutableSequence[str]): - Contains information about the impact of this - vulnerability, this will change with time. - remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): - Specifies details on how to handle (and - presumably, fix) a vulnerability. - justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): - Justification provides the justification when the state of - the assessment if NOT_AFFECTED. - """ - - cve: str = proto.Field( - proto.STRING, - number=1, - ) - vulnerability_id: str = proto.Field( - proto.STRING, - number=8, - ) - related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.RelatedUrl, - ) - note_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: vex.VulnerabilityAssessmentNote.Assessment.State = proto.Field( - proto.ENUM, - number=4, - enum=vex.VulnerabilityAssessmentNote.Assessment.State, - ) - impacts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - remediations: MutableSequence[ - vex.VulnerabilityAssessmentNote.Assessment.Remediation - ] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=vex.VulnerabilityAssessmentNote.Assessment.Remediation, - ) - justification: vex.VulnerabilityAssessmentNote.Assessment.Justification = ( - proto.Field( - proto.MESSAGE, - number=7, - message=vex.VulnerabilityAssessmentNote.Assessment.Justification, - ) - ) - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=2, - enum=g_severity.Severity, - ) - cvss_score: float = proto.Field( - proto.FLOAT, - number=3, - ) - cvssv3: cvss.CVSS = proto.Field( - proto.MESSAGE, - number=10, - message=cvss.CVSS, - ) - package_issue: MutableSequence[PackageIssue] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=PackageIssue, - ) - short_description: str = proto.Field( - proto.STRING, - number=5, - ) - long_description: str = proto.Field( - proto.STRING, - number=6, - ) - related_urls: MutableSequence[common.RelatedUrl] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=common.RelatedUrl, - ) - effective_severity: g_severity.Severity = proto.Field( - proto.ENUM, - number=8, - enum=g_severity.Severity, - ) - fix_available: bool = proto.Field( - proto.BOOL, - number=9, - ) - cvss_version: cvss.CVSSVersion = proto.Field( - proto.ENUM, - number=11, - enum=cvss.CVSSVersion, - ) - cvss_v2: cvss.CVSS = proto.Field( - proto.MESSAGE, - number=12, - message=cvss.CVSS, - ) - vex_assessment: VexAssessment = proto.Field( - proto.MESSAGE, - number=13, - message=VexAssessment, - ) - extra_details: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/mypy.ini b/packages/grafeas/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/packages/grafeas/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/packages/grafeas/noxfile.py b/packages/grafeas/noxfile.py deleted file mode 100644 index 920f8c0eed03..000000000000 --- a/packages/grafeas/noxfile.py +++ /dev/null @@ -1,616 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "grafeas", "tests", "noxfile.py", "setup.py"] - -# Add samples to the list of directories to format if the directory exists. -if os.path.isdir("samples"): - LINT_PATHS.append("samples") - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", - "3.14", -] - -DEFAULT_PYTHON_VERSION = "3.14" - -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2450): -# Switch this to Python 3.15 alpha1 -# https://peps.python.org/pep-0790/ -PREVIEW_PYTHON_VERSION = "3.14" - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "grafeas" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ALL_PYTHON -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "grafeas", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "grafeas", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # 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", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): - # Remove this check once support for Protobuf 3.x is dropped. - if protobuf_implementation == "cpp" and session.python in ( - "3.11", - "3.12", - "3.13", - "3.14", - ): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=grafeas", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.0", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", # builder - "-d", - os.path.join("docs", "_build", "doctrees", ""), # cache directory - # paths to build: - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=PREVIEW_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): - # Remove this check once support for Protobuf 3.x is dropped. - if protobuf_implementation == "cpp" and session.python in ( - "3.11", - "3.12", - "3.13", - "3.14", - ): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py deleted file mode 100644 index d4dbb666e68a..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_notes(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py deleted file mode 100644 index bb47c162409a..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_batch_create_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_notes(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py deleted file mode 100644 index 94bf30631275..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py deleted file mode 100644 index 1a7d8c94f3d7..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchCreateOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_batch_create_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_create_occurrences(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py deleted file mode 100644 index a6f20ad35fd6..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateNote_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = await client.create_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_CreateNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py deleted file mode 100644 index 17f008cfc9b4..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateNote_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_create_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Make the request - response = client.create_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_CreateNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py deleted file mode 100644 index c5e8655287ac..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_occurrence(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py deleted file mode 100644 index a7917a129f81..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_create_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_occurrence(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py deleted file mode 100644 index de9803c48ca3..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteNote_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - await client.delete_note(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py deleted file mode 100644 index ad68fec3afc4..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteNote_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_delete_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteNoteRequest( - name="name_value", - ) - - # Make the request - client.delete_note(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py deleted file mode 100644 index 7872f4448244..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - await client.delete_occurrence(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py deleted file mode 100644 index 5786e6e336bd..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_delete_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.DeleteOccurrenceRequest( - name="name_value", - ) - - # Make the request - client.delete_occurrence(request=request) - - -# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py deleted file mode 100644 index 7382d5221d8f..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetNote_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_GetNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py deleted file mode 100644 index e01d8954481b..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetNote_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_get_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_GetNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py deleted file mode 100644 index 95342437e6ee..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py deleted file mode 100644 index d6a5bcc7ddaf..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrenceNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.get_occurrence_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py deleted file mode 100644 index e95b8e53d000..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrenceNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_get_occurrence_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py deleted file mode 100644 index 5f7e7278bf24..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_get_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.GetOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.get_occurrence(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py deleted file mode 100644 index 1113c13621c1..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNoteOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py deleted file mode 100644 index 17595ad29d0d..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNoteOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_list_note_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNoteOccurrencesRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_note_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py deleted file mode 100644 index fad196861bad..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNotes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_ListNotes_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py deleted file mode 100644 index 0085885671e6..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListNotes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListNotes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_list_notes(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListNotesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notes(request=request) - - # Handle the response - for response in page_result: - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_ListNotes_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py deleted file mode 100644 index 58b47a402faa..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - async for response in page_result: - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py deleted file mode 100644 index 6d4509711c33..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListOccurrences -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_list_occurrences(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.ListOccurrencesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_occurrences(request=request) - - # Handle the response - for response in page_result: - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py deleted file mode 100644 index b2a97d0ddfe6..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateNote_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = await client.update_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_UpdateNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py deleted file mode 100644 index d317cda50836..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateNote -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateNote_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_update_note(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateNoteRequest( - name="name_value", - ) - - # Make the request - response = client.update_note(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_UpdateNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py deleted file mode 100644 index 6ff6ffa77959..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -async def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasAsyncClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = await client.update_occurrence(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py deleted file mode 100644 index 4a523c540c5a..000000000000 --- a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateOccurrence -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install grafeas - - -# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from grafeas import grafeas_v1 - - -def sample_update_occurrence(): - # Create a client - client = grafeas_v1.GrafeasClient() - - # Initialize request argument(s) - request = grafeas_v1.UpdateOccurrenceRequest( - name="name_value", - ) - - # Make the request - response = client.update_occurrence(request=request) - - # Handle the response - print(response) - - -# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json deleted file mode 100644 index 7f54da166386..000000000000 --- a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json +++ /dev/null @@ -1,2353 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "grafeas.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "grafeas", - "version": "1.16.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notes", - "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", - "shortName": "batch_create_notes" - }, - "description": "Sample for BatchCreateNotes", - "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notes", - "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", - "shortName": "batch_create_notes" - }, - "description": "Sample for BatchCreateNotes", - "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrences", - "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", - "shortName": "batch_create_occurrences" - }, - "description": "Sample for BatchCreateOccurrences", - "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "BatchCreateOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrences", - "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", - "shortName": "batch_create_occurrences" - }, - "description": "Sample for BatchCreateOccurrences", - "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_note", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateNoteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "note_id", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "create_note" - }, - "description": "Sample for CreateNote", - "file": "containeranalysis_v1_generated_grafeas_create_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_create_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.create_note", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateNoteRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "note_id", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "create_note" - }, - "description": "Sample for CreateNote", - "file": "containeranalysis_v1_generated_grafeas_create_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_create_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "create_occurrence" - }, - "description": "Sample for CreateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.create_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.CreateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "CreateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "create_occurrence" - }, - "description": "Sample for CreateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_note", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_note" - }, - "description": "Sample for DeleteNote", - "file": "containeranalysis_v1_generated_grafeas_delete_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_delete_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_note", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_note" - }, - "description": "Sample for DeleteNote", - "file": "containeranalysis_v1_generated_grafeas_delete_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_delete_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_occurrence" - }, - "description": "Sample for DeleteOccurrence", - "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "DeleteOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "shortName": "delete_occurrence" - }, - "description": "Sample for DeleteOccurrence", - "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "get_note" - }, - "description": "Sample for GetNote", - "file": "containeranalysis_v1_generated_grafeas_get_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_get_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.get_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "get_note" - }, - "description": "Sample for GetNote", - "file": "containeranalysis_v1_generated_grafeas_get_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_get_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrenceNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "get_occurrence_note" - }, - "description": "Sample for GetOccurrenceNote", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence_note", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrenceNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "get_occurrence_note" - }, - "description": "Sample for GetOccurrenceNote", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "get_occurrence" - }, - "description": "Sample for GetOccurrence", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.GetOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "GetOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "get_occurrence" - }, - "description": "Sample for GetOccurrence", - "file": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_note_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNoteOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager", - "shortName": "list_note_occurrences" - }, - "description": "Sample for ListNoteOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.list_note_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNoteOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager", - "shortName": "list_note_occurrences" - }, - "description": "Sample for ListNoteOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager", - "shortName": "list_notes" - }, - "description": "Sample for ListNotes", - "file": "containeranalysis_v1_generated_grafeas_list_notes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_list_notes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.list_notes", - "method": { - "fullName": "grafeas.v1.Grafeas.ListNotes", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListNotes" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListNotesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager", - "shortName": "list_notes" - }, - "description": "Sample for ListNotes", - "file": "containeranalysis_v1_generated_grafeas_list_notes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_list_notes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager", - "shortName": "list_occurrences" - }, - "description": "Sample for ListOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.list_occurrences", - "method": { - "fullName": "grafeas.v1.Grafeas.ListOccurrences", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "ListOccurrences" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager", - "shortName": "list_occurrences" - }, - "description": "Sample for ListOccurrences", - "file": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_note", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "update_note" - }, - "description": "Sample for UpdateNote", - "file": "containeranalysis_v1_generated_grafeas_update_note_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_update_note_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.update_note", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateNote", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateNote" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "note", - "type": "grafeas.grafeas_v1.types.Note" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Note", - "shortName": "update_note" - }, - "description": "Sample for UpdateNote", - "file": "containeranalysis_v1_generated_grafeas_update_note_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_update_note_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", - "shortName": "GrafeasAsyncClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "update_occurrence" - }, - "description": "Sample for UpdateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "grafeas.grafeas_v1.GrafeasClient", - "shortName": "GrafeasClient" - }, - "fullName": "grafeas.grafeas_v1.GrafeasClient.update_occurrence", - "method": { - "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", - "service": { - "fullName": "grafeas.v1.Grafeas", - "shortName": "Grafeas" - }, - "shortName": "UpdateOccurrence" - }, - "parameters": [ - { - "name": "request", - "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "occurrence", - "type": "grafeas.grafeas_v1.types.Occurrence" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "grafeas.grafeas_v1.types.Occurrence", - "shortName": "update_occurrence" - }, - "description": "Sample for UpdateOccurrence", - "file": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py" - } - ] -} diff --git a/packages/grafeas/scripts/fixup_grafeas_v1_keywords.py b/packages/grafeas/scripts/fixup_grafeas_v1_keywords.py deleted file mode 100644 index 6bb7b21dda4f..000000000000 --- a/packages/grafeas/scripts/fixup_grafeas_v1_keywords.py +++ /dev/null @@ -1,189 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class grafeasCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_notes': ('parent', 'notes', ), - 'batch_create_occurrences': ('parent', 'occurrences', ), - 'create_note': ('parent', 'note_id', 'note', ), - 'create_occurrence': ('parent', 'occurrence', ), - 'delete_note': ('name', ), - 'delete_occurrence': ('name', ), - 'get_note': ('name', ), - 'get_occurrence': ('name', ), - 'get_occurrence_note': ('name', ), - 'list_note_occurrences': ('name', 'filter', 'page_size', 'page_token', ), - 'list_notes': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_occurrences': ('parent', 'filter', 'page_size', 'page_token', ), - 'update_note': ('name', 'note', 'update_mask', ), - 'update_occurrence': ('name', 'occurrence', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=grafeasCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the grafeas client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/packages/grafeas/setup.py b/packages/grafeas/setup.py deleted file mode 100644 index 6689233a0971..000000000000 --- a/packages/grafeas/setup.py +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 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 io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = "grafeas" - - -description = "Grafeas API client library" - -version = None - -with open(os.path.join(package_root, "grafeas/grafeas/gapic_version.py")) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert len(version_candidates) == 1 - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "grpcio >= 1.33.2, < 2.0.0", - "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -extras = {} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("grafeas") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.14", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/packages/grafeas/testing/constraints-3.10.txt b/packages/grafeas/testing/constraints-3.10.txt deleted file mode 100644 index 93e6826f2af9..000000000000 --- a/packages/grafeas/testing/constraints-3.10.txt +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf diff --git a/packages/grafeas/testing/constraints-3.11.txt b/packages/grafeas/testing/constraints-3.11.txt deleted file mode 100644 index 93e6826f2af9..000000000000 --- a/packages/grafeas/testing/constraints-3.11.txt +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf diff --git a/packages/grafeas/testing/constraints-3.12.txt b/packages/grafeas/testing/constraints-3.12.txt deleted file mode 100644 index 93e6826f2af9..000000000000 --- a/packages/grafeas/testing/constraints-3.12.txt +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf diff --git a/packages/grafeas/testing/constraints-3.13.txt b/packages/grafeas/testing/constraints-3.13.txt deleted file mode 100644 index 1e93c60e50aa..000000000000 --- a/packages/grafeas/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -grpcio>=1 -proto-plus>=1 -protobuf>=6 diff --git a/packages/grafeas/testing/constraints-3.14.txt b/packages/grafeas/testing/constraints-3.14.txt deleted file mode 100644 index 1e93c60e50aa..000000000000 --- a/packages/grafeas/testing/constraints-3.14.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -grpcio>=1 -proto-plus>=1 -protobuf>=6 diff --git a/packages/grafeas/testing/constraints-3.7.txt b/packages/grafeas/testing/constraints-3.7.txt deleted file mode 100644 index 5d29dea38698..000000000000 --- a/packages/grafeas/testing/constraints-3.7.txt +++ /dev/null @@ -1,12 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2453) -# Add the minimum supported version of grpcio to constraints files -proto-plus==1.22.3 -protobuf==3.20.2 diff --git a/packages/grafeas/testing/constraints-3.8.txt b/packages/grafeas/testing/constraints-3.8.txt deleted file mode 100644 index 93e6826f2af9..000000000000 --- a/packages/grafeas/testing/constraints-3.8.txt +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf diff --git a/packages/grafeas/testing/constraints-3.9.txt b/packages/grafeas/testing/constraints-3.9.txt deleted file mode 100644 index 93e6826f2af9..000000000000 --- a/packages/grafeas/testing/constraints-3.9.txt +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf diff --git a/packages/grafeas/tests/__init__.py b/packages/grafeas/tests/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/packages/grafeas/tests/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/packages/grafeas/tests/unit/__init__.py b/packages/grafeas/tests/unit/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/packages/grafeas/tests/unit/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/packages/grafeas/tests/unit/gapic/__init__.py b/packages/grafeas/tests/unit/gapic/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/packages/grafeas/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py b/packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py b/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py deleted file mode 100644 index 454c0fd5f768..000000000000 --- a/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py +++ /dev/null @@ -1,13188 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os - -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -from collections.abc import AsyncIterable, Iterable -import json -import math - -from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -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 - -try: - from google.auth.aio import credentials as ga_credentials_async - - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - -from grafeas.grafeas_v1.services.grafeas import ( - GrafeasAsyncClient, - GrafeasClient, - pagers, - transports, -) -from grafeas.grafeas_v1.types import ( - attestation, - build, - common, - compliance, - cvss, - deployment, - discovery, - dsse_attestation, - grafeas, - image, - intoto_provenance, - intoto_statement, - package, - provenance, - sbom, - secret, - severity, - slsa_provenance, - slsa_provenance_zero_two, - upgrade, - vex, - vulnerability, -) - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.GetOccurrenceRequest, - dict, - ], -) -def test_get_occurrence(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - response = client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -def test_get_occurrence_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.GetOccurrenceRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceRequest( - name="name_value", - ) - - -def test_get_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_occurrence] = mock_rpc - request = {} - client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_get_occurrence_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.get_occurrence - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_occurrence - ] = mock_rpc - - request = {} - await client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_get_occurrence_async( - transport: str = "grpc_asyncio", request_type=grafeas.GetOccurrenceRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - ) - response = await client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -@pytest.mark.asyncio -async def test_get_occurrence_async_from_dict(): - await test_get_occurrence_async(request_type=dict) - - -def test_get_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.GetOccurrenceRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - call.return_value = grafeas.Occurrence() - client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetOccurrenceRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_get_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_occurrence( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_get_occurrence_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_occurrence( - grafeas.GetOccurrenceRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_get_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_occurrence( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_get_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_occurrence( - grafeas.GetOccurrenceRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.ListOccurrencesRequest, - dict, - ], -) -def test_list_occurrences(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse( - next_page_token="next_page_token_value", - ) - response = client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.ListOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_occurrences_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.ListOccurrencesRequest( - parent="parent_value", - filter="filter_value", - page_token="page_token_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_occurrences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListOccurrencesRequest( - parent="parent_value", - filter="filter_value", - page_token="page_token_value", - ) - - -def test_list_occurrences_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_occurrences - ] = mock_rpc - request = {} - client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_occurrences_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.list_occurrences - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_occurrences - ] = mock_rpc - - request = {} - await client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_occurrences_async( - transport: str = "grpc_asyncio", request_type=grafeas.ListOccurrencesRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListOccurrencesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.ListOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesAsyncPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.asyncio -async def test_list_occurrences_async_from_dict(): - await test_list_occurrences_async(request_type=dict) - - -def test_list_occurrences_field_headers(): - client = GrafeasClient( - 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 = grafeas.ListOccurrencesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - call.return_value = grafeas.ListOccurrencesResponse() - client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_list_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListOccurrencesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListOccurrencesResponse() - ) - await client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_list_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_occurrences( - parent="parent_value", - filter="filter_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" - assert arg == mock_val - - -def test_list_occurrences_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_occurrences( - grafeas.ListOccurrencesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -@pytest.mark.asyncio -async def test_list_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListOccurrencesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_occurrences( - parent="parent_value", - filter="filter_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_occurrences( - grafeas.ListOccurrencesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_list_occurrences_pager(transport_name: str = "grpc"): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_occurrences(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) for i in results) - - -def test_list_occurrences_pages(transport_name: str = "grpc"): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = list(client.list_occurrences(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_occurrences_async_pager(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_occurrences( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, grafeas.Occurrence) for i in responses) - - -@pytest.mark.asyncio -async def test_list_occurrences_async_pages(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_occurrences), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_occurrences(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.DeleteOccurrenceRequest, - dict, - ], -) -def test_delete_occurrence(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_occurrence_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.DeleteOccurrenceRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteOccurrenceRequest( - name="name_value", - ) - - -def test_delete_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_occurrence - ] = mock_rpc - request = {} - client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_delete_occurrence_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.delete_occurrence - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_occurrence - ] = mock_rpc - - request = {} - await client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_delete_occurrence_async( - transport: str = "grpc_asyncio", request_type=grafeas.DeleteOccurrenceRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteOccurrenceRequest() - 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_occurrence_async_from_dict(): - await test_delete_occurrence_async(request_type=dict) - - -def test_delete_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.DeleteOccurrenceRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - call.return_value = None - client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_delete_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.DeleteOccurrenceRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_delete_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_occurrence( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_delete_occurrence_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_occurrence( - grafeas.DeleteOccurrenceRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_delete_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_occurrence( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_delete_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_occurrence( - grafeas.DeleteOccurrenceRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.CreateOccurrenceRequest, - dict, - ], -) -def test_create_occurrence(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - response = client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.CreateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -def test_create_occurrence_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.CreateOccurrenceRequest( - parent="parent_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateOccurrenceRequest( - parent="parent_value", - ) - - -def test_create_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_occurrence - ] = mock_rpc - request = {} - client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_occurrence_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.create_occurrence - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_occurrence - ] = mock_rpc - - request = {} - await client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_occurrence_async( - transport: str = "grpc_asyncio", request_type=grafeas.CreateOccurrenceRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - ) - response = await client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.CreateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -@pytest.mark.asyncio -async def test_create_occurrence_async_from_dict(): - await test_create_occurrence_async(request_type=dict) - - -def test_create_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.CreateOccurrenceRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - call.return_value = grafeas.Occurrence() - client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_create_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.CreateOccurrenceRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_create_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_occurrence( - parent="parent_value", - occurrence=grafeas.Occurrence(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].occurrence - mock_val = grafeas.Occurrence(name="name_value") - assert arg == mock_val - - -def test_create_occurrence_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_occurrence( - grafeas.CreateOccurrenceRequest(), - parent="parent_value", - occurrence=grafeas.Occurrence(name="name_value"), - ) - - -@pytest.mark.asyncio -async def test_create_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_occurrence( - parent="parent_value", - occurrence=grafeas.Occurrence(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].occurrence - mock_val = grafeas.Occurrence(name="name_value") - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_occurrence( - grafeas.CreateOccurrenceRequest(), - parent="parent_value", - occurrence=grafeas.Occurrence(name="name_value"), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.BatchCreateOccurrencesRequest, - dict, - ], -) -def test_batch_create_occurrences(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - response = client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -def test_batch_create_occurrences_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_create_occurrences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateOccurrencesRequest( - parent="parent_value", - ) - - -def test_batch_create_occurrences_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.batch_create_occurrences - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_create_occurrences - ] = mock_rpc - request = {} - client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.batch_create_occurrences - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_create_occurrences - ] = mock_rpc - - request = {} - await client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.batch_create_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async( - transport: str = "grpc_asyncio", request_type=grafeas.BatchCreateOccurrencesRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateOccurrencesResponse() - ) - response = await client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_async_from_dict(): - await test_batch_create_occurrences_async(request_type=dict) - - -def test_batch_create_occurrences_field_headers(): - client = GrafeasClient( - 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 = grafeas.BatchCreateOccurrencesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - call.return_value = grafeas.BatchCreateOccurrencesResponse() - client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.BatchCreateOccurrencesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateOccurrencesResponse() - ) - await client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_batch_create_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_occurrences( - parent="parent_value", - occurrences=[grafeas.Occurrence(name="name_value")], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].occurrences - mock_val = [grafeas.Occurrence(name="name_value")] - assert arg == mock_val - - -def test_batch_create_occurrences_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent="parent_value", - occurrences=[grafeas.Occurrence(name="name_value")], - ) - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateOccurrencesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_occurrences( - parent="parent_value", - occurrences=[grafeas.Occurrence(name="name_value")], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].occurrences - mock_val = [grafeas.Occurrence(name="name_value")] - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_batch_create_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent="parent_value", - occurrences=[grafeas.Occurrence(name="name_value")], - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.UpdateOccurrenceRequest, - dict, - ], -) -def test_update_occurrence(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - response = client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -def test_update_occurrence_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.UpdateOccurrenceRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_occurrence(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateOccurrenceRequest( - name="name_value", - ) - - -def test_update_occurrence_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_occurrence - ] = mock_rpc - request = {} - client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_update_occurrence_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.update_occurrence - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_occurrence - ] = mock_rpc - - request = {} - await client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_update_occurrence_async( - transport: str = "grpc_asyncio", request_type=grafeas.UpdateOccurrenceRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - ) - response = await client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateOccurrenceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -@pytest.mark.asyncio -async def test_update_occurrence_async_from_dict(): - await test_update_occurrence_async(request_type=dict) - - -def test_update_occurrence_field_headers(): - client = GrafeasClient( - 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 = grafeas.UpdateOccurrenceRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - call.return_value = grafeas.Occurrence() - client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_update_occurrence_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.UpdateOccurrenceRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - await client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_update_occurrence_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_occurrence( - name="name_value", - occurrence=grafeas.Occurrence(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].occurrence - mock_val = grafeas.Occurrence(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_occurrence_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_occurrence( - grafeas.UpdateOccurrenceRequest(), - name="name_value", - occurrence=grafeas.Occurrence(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_occurrence_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Occurrence() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_occurrence( - name="name_value", - occurrence=grafeas.Occurrence(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].occurrence - mock_val = grafeas.Occurrence(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_occurrence_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_occurrence( - grafeas.UpdateOccurrenceRequest(), - name="name_value", - occurrence=grafeas.Occurrence(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.GetOccurrenceNoteRequest, - dict, - ], -) -def test_get_occurrence_note(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - response = client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -def test_get_occurrence_note_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.GetOccurrenceNoteRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_occurrence_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetOccurrenceNoteRequest( - name="name_value", - ) - - -def test_get_occurrence_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.get_occurrence_note in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_occurrence_note - ] = mock_rpc - request = {} - client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_get_occurrence_note_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.get_occurrence_note - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_occurrence_note - ] = mock_rpc - - request = {} - await client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_occurrence_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_get_occurrence_note_async( - transport: str = "grpc_asyncio", request_type=grafeas.GetOccurrenceNoteRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - response = await client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.GetOccurrenceNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.asyncio -async def test_get_occurrence_note_async_from_dict(): - await test_get_occurrence_note_async(request_type=dict) - - -def test_get_occurrence_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.GetOccurrenceNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - call.return_value = grafeas.Note() - client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_occurrence_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetOccurrenceNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_get_occurrence_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_occurrence_note( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_get_occurrence_note_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_get_occurrence_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_occurrence_note( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_get_occurrence_note_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.GetNoteRequest, - dict, - ], -) -def test_get_note(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - response = client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.GetNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -def test_get_note_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.GetNoteRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.GetNoteRequest( - name="name_value", - ) - - -def test_get_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_note] = mock_rpc - request = {} - client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_get_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.get_note - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_note - ] = mock_rpc - - request = {} - await client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_get_note_async( - transport: str = "grpc_asyncio", request_type=grafeas.GetNoteRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - response = await client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.GetNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.asyncio -async def test_get_note_async_from_dict(): - await test_get_note_async(request_type=dict) - - -def test_get_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.GetNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - call.return_value = grafeas.Note() - client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.GetNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_get_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_note( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_get_note_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_note( - grafeas.GetNoteRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_get_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_note( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_get_note_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_note( - grafeas.GetNoteRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.ListNotesRequest, - dict, - ], -) -def test_list_notes(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse( - next_page_token="next_page_token_value", - ) - response = client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.ListNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_notes_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.ListNotesRequest( - parent="parent_value", - filter="filter_value", - page_token="page_token_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_notes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNotesRequest( - parent="parent_value", - filter="filter_value", - page_token="page_token_value", - ) - - -def test_list_notes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_notes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.list_notes] = mock_rpc - request = {} - client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_notes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.list_notes - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_notes - ] = mock_rpc - - request = {} - await client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_notes_async( - transport: str = "grpc_asyncio", request_type=grafeas.ListNotesRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNotesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.ListNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesAsyncPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.asyncio -async def test_list_notes_async_from_dict(): - await test_list_notes_async(request_type=dict) - - -def test_list_notes_field_headers(): - client = GrafeasClient( - 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 = grafeas.ListNotesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - call.return_value = grafeas.ListNotesResponse() - client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_list_notes_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListNotesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNotesResponse() - ) - await client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_list_notes_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notes( - parent="parent_value", - filter="filter_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" - assert arg == mock_val - - -def test_list_notes_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_notes( - grafeas.ListNotesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -@pytest.mark.asyncio -async def test_list_notes_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNotesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNotesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notes( - parent="parent_value", - filter="filter_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_notes_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notes( - grafeas.ListNotesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_list_notes_pager(transport_name: str = "grpc"): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token="abc", - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token="def", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token="ghi", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_notes(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Note) for i in results) - - -def test_list_notes_pages(transport_name: str = "grpc"): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token="abc", - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token="def", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token="ghi", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notes(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_notes_async_pager(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token="abc", - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token="def", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token="ghi", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notes( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, grafeas.Note) for i in responses) - - -@pytest.mark.asyncio -async def test_list_notes_async_pages(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notes), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token="abc", - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token="def", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token="ghi", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_notes(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.DeleteNoteRequest, - dict, - ], -) -def test_delete_note(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_note_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.DeleteNoteRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.DeleteNoteRequest( - name="name_value", - ) - - -def test_delete_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.delete_note] = mock_rpc - request = {} - client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_delete_note_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.delete_note - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_note - ] = mock_rpc - - request = {} - await client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_delete_note_async( - transport: str = "grpc_asyncio", request_type=grafeas.DeleteNoteRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.DeleteNoteRequest() - 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_note_async_from_dict(): - await test_delete_note_async(request_type=dict) - - -def test_delete_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.DeleteNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - call.return_value = None - client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_delete_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.DeleteNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_delete_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_note( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_delete_note_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_note( - grafeas.DeleteNoteRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_delete_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_note( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_delete_note_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_note( - grafeas.DeleteNoteRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.CreateNoteRequest, - dict, - ], -) -def test_create_note(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - response = client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.CreateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -def test_create_note_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.CreateNoteRequest( - parent="parent_value", - note_id="note_id_value", - ) - - -def test_create_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_note] = mock_rpc - request = {} - client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_note_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.create_note - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_note - ] = mock_rpc - - request = {} - await client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_note_async( - transport: str = "grpc_asyncio", request_type=grafeas.CreateNoteRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - response = await client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.CreateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.asyncio -async def test_create_note_async_from_dict(): - await test_create_note_async(request_type=dict) - - -def test_create_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.CreateNoteRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - call.return_value = grafeas.Note() - client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_create_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.CreateNoteRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_create_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_note( - parent="parent_value", - note_id="note_id_value", - note=grafeas.Note(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].note_id - mock_val = "note_id_value" - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(name="name_value") - assert arg == mock_val - - -def test_create_note_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_note( - grafeas.CreateNoteRequest(), - parent="parent_value", - note_id="note_id_value", - note=grafeas.Note(name="name_value"), - ) - - -@pytest.mark.asyncio -async def test_create_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_note( - parent="parent_value", - note_id="note_id_value", - note=grafeas.Note(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].note_id - mock_val = "note_id_value" - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(name="name_value") - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_note_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_note( - grafeas.CreateNoteRequest(), - parent="parent_value", - note_id="note_id_value", - note=grafeas.Note(name="name_value"), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.BatchCreateNotesRequest, - dict, - ], -) -def test_batch_create_notes(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - response = client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -def test_batch_create_notes_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.BatchCreateNotesRequest( - parent="parent_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_create_notes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.BatchCreateNotesRequest( - parent="parent_value", - ) - - -def test_batch_create_notes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.batch_create_notes in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_create_notes - ] = mock_rpc - request = {} - client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_batch_create_notes_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.batch_create_notes - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_create_notes - ] = mock_rpc - - request = {} - await client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.batch_create_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_batch_create_notes_async( - transport: str = "grpc_asyncio", request_type=grafeas.BatchCreateNotesRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateNotesResponse() - ) - response = await client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.BatchCreateNotesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -@pytest.mark.asyncio -async def test_batch_create_notes_async_from_dict(): - await test_batch_create_notes_async(request_type=dict) - - -def test_batch_create_notes_field_headers(): - client = GrafeasClient( - 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 = grafeas.BatchCreateNotesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - call.return_value = grafeas.BatchCreateNotesResponse() - client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_batch_create_notes_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.BatchCreateNotesRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateNotesResponse() - ) - await client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] - - -def test_batch_create_notes_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_notes( - parent="parent_value", - notes={"key_value": grafeas.Note(name="name_value")}, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].notes - mock_val = {"key_value": grafeas.Note(name="name_value")} - assert arg == mock_val - - -def test_batch_create_notes_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent="parent_value", - notes={"key_value": grafeas.Note(name="name_value")}, - ) - - -@pytest.mark.asyncio -async def test_batch_create_notes_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.BatchCreateNotesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateNotesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_notes( - parent="parent_value", - notes={"key_value": grafeas.Note(name="name_value")}, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].notes - mock_val = {"key_value": grafeas.Note(name="name_value")} - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_batch_create_notes_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent="parent_value", - notes={"key_value": grafeas.Note(name="name_value")}, - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.UpdateNoteRequest, - dict, - ], -) -def test_update_note(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - response = client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -def test_update_note_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.UpdateNoteRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_note(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.UpdateNoteRequest( - name="name_value", - ) - - -def test_update_note_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_note] = mock_rpc - request = {} - client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_update_note_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.update_note - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_note - ] = mock_rpc - - request = {} - await client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_update_note_async( - transport: str = "grpc_asyncio", request_type=grafeas.UpdateNoteRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - response = await client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.UpdateNoteRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.asyncio -async def test_update_note_async_from_dict(): - await test_update_note_async(request_type=dict) - - -def test_update_note_field_headers(): - client = GrafeasClient( - 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 = grafeas.UpdateNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - call.return_value = grafeas.Note() - client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_update_note_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.UpdateNoteRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - await client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_update_note_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_note( - name="name_value", - note=grafeas.Note(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_note_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_note( - grafeas.UpdateNoteRequest(), - name="name_value", - note=grafeas.Note(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_note_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.Note() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_note( - name="name_value", - note=grafeas.Note(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].note - mock_val = grafeas.Note(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_note_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_note( - grafeas.UpdateNoteRequest(), - name="name_value", - note=grafeas.Note(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.ListNoteOccurrencesRequest, - dict, - ], -) -def test_list_note_occurrences(request_type, transport: str = "grpc"): - client = GrafeasClient( - 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 = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse( - next_page_token="next_page_token_value", - ) - response = client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = grafeas.ListNoteOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_note_occurrences_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = grafeas.ListNoteOccurrencesRequest( - name="name_value", - filter="filter_value", - page_token="page_token_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_note_occurrences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == grafeas.ListNoteOccurrencesRequest( - name="name_value", - filter="filter_value", - page_token="page_token_value", - ) - - -def test_list_note_occurrences_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_note_occurrences - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_note_occurrences - ] = mock_rpc - request = {} - client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_note_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.list_note_occurrences - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_note_occurrences - ] = mock_rpc - - request = {} - await client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_note_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async( - transport: str = "grpc_asyncio", request_type=grafeas.ListNoteOccurrencesRequest -): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNoteOccurrencesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = grafeas.ListNoteOccurrencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesAsyncPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_from_dict(): - await test_list_note_occurrences_async(request_type=dict) - - -def test_list_note_occurrences_field_headers(): - client = GrafeasClient( - 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 = grafeas.ListNoteOccurrencesRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - call.return_value = grafeas.ListNoteOccurrencesResponse() - client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_list_note_occurrences_field_headers_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grafeas.ListNoteOccurrencesRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNoteOccurrencesResponse() - ) - await client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_list_note_occurrences_flattened(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_note_occurrences( - name="name_value", - filter="filter_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" - assert arg == mock_val - - -def test_list_note_occurrences_flattened_error(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name="name_value", - filter="filter_value", - ) - - -@pytest.mark.asyncio -async def test_list_note_occurrences_flattened_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grafeas.ListNoteOccurrencesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNoteOccurrencesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_note_occurrences( - name="name_value", - filter="filter_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_note_occurrences_flattened_error_async(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name="name_value", - filter="filter_value", - ) - - -def test_list_note_occurrences_pager(transport_name: str = "grpc"): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), - ) - pager = client.list_note_occurrences(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) for i in results) - - -def test_list_note_occurrences_pages(transport_name: str = "grpc"): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = list(client.list_note_occurrences(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_pager(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_note_occurrences( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, grafeas.Occurrence) for i in responses) - - -@pytest.mark.asyncio -async def test_list_note_occurrences_async_pages(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_note_occurrences(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_occurrence_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_occurrence] = mock_rpc - - request = {} - client.get_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_occurrence_rest_required_fields(request_type=grafeas.GetOccurrenceRequest): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_occurrence._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_occurrence._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Occurrence() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_occurrence(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_get_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.get_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_get_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Occurrence() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/occurrences/sample2"} - - # 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 - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_occurrence(**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/*/occurrences/*}" % client.transport._host, args[1] - ) - - -def test_get_occurrence_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_occurrence( - grafeas.GetOccurrenceRequest(), - name="name_value", - ) - - -def test_list_occurrences_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_occurrences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_occurrences - ] = mock_rpc - - request = {} - client.list_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_occurrences_rest_required_fields( - request_type=grafeas.ListOccurrencesRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_occurrences._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_occurrences._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.ListOccurrencesResponse() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.ListOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_occurrences(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_list_occurrences_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_occurrences._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) - - -def test_list_occurrences_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.ListOccurrencesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - filter="filter_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.ListOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_occurrences(**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/*}/occurrences" % client.transport._host, args[1] - ) - - -def test_list_occurrences_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_occurrences( - grafeas.ListOccurrencesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_list_occurrences_rest_pager(transport: str = "rest"): - client = GrafeasClient( - 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 = ( - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(grafeas.ListOccurrencesResponse.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"} - - pager = client.list_occurrences(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) for i in results) - - pages = list(client.list_occurrences(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_occurrence_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_occurrence - ] = mock_rpc - - request = {} - client.delete_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_occurrence_rest_required_fields( - request_type=grafeas.DeleteOccurrenceRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_occurrence._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_occurrence._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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 = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_occurrence(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_delete_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.delete_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_delete_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/occurrences/sample2"} - - # 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 = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_occurrence(**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/*/occurrences/*}" % client.transport._host, args[1] - ) - - -def test_delete_occurrence_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_occurrence( - grafeas.DeleteOccurrenceRequest(), - name="name_value", - ) - - -def test_create_occurrence_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_occurrence - ] = mock_rpc - - request = {} - client.create_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_occurrence_rest_required_fields( - request_type=grafeas.CreateOccurrenceRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_occurrence._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_occurrence._get_unset_required_fields(jsonified_request) - 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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Occurrence() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_occurrence(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_create_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.create_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "occurrence", - ) - ) - ) - - -def test_create_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Occurrence() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - occurrence=grafeas.Occurrence(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_occurrence(**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/*}/occurrences" % client.transport._host, args[1] - ) - - -def test_create_occurrence_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_occurrence( - grafeas.CreateOccurrenceRequest(), - parent="parent_value", - occurrence=grafeas.Occurrence(name="name_value"), - ) - - -def test_batch_create_occurrences_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.batch_create_occurrences - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_create_occurrences - ] = mock_rpc - - request = {} - client.batch_create_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_batch_create_occurrences_rest_required_fields( - request_type=grafeas.BatchCreateOccurrencesRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_create_occurrences._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() - ).batch_create_occurrences._get_unset_required_fields(jsonified_request) - 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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.BatchCreateOccurrencesResponse() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.BatchCreateOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.batch_create_occurrences(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_batch_create_occurrences_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.batch_create_occurrences._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "occurrences", - ) - ) - ) - - -def test_batch_create_occurrences_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.BatchCreateOccurrencesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - occurrences=[grafeas.Occurrence(name="name_value")], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.BatchCreateOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.batch_create_occurrences(**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/*}/occurrences:batchCreate" - % client.transport._host, - args[1], - ) - - -def test_batch_create_occurrences_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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.batch_create_occurrences( - grafeas.BatchCreateOccurrencesRequest(), - parent="parent_value", - occurrences=[grafeas.Occurrence(name="name_value")], - ) - - -def test_update_occurrence_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_occurrence in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_occurrence - ] = mock_rpc - - request = {} - client.update_occurrence(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_occurrence(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_occurrence_rest_required_fields( - request_type=grafeas.UpdateOccurrenceRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_occurrence._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() - ).update_occurrence._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) - 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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Occurrence() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_occurrence(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_update_occurrence_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.update_occurrence._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "name", - "occurrence", - ) - ) - ) - - -def test_update_occurrence_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Occurrence() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/occurrences/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - occurrence=grafeas.Occurrence(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 - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_occurrence(**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/*/occurrences/*}" % client.transport._host, args[1] - ) - - -def test_update_occurrence_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_occurrence( - grafeas.UpdateOccurrenceRequest(), - name="name_value", - occurrence=grafeas.Occurrence(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_get_occurrence_note_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.get_occurrence_note in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_occurrence_note - ] = mock_rpc - - request = {} - client.get_occurrence_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_occurrence_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_occurrence_note_rest_required_fields( - request_type=grafeas.GetOccurrenceNoteRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_occurrence_note._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_occurrence_note._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_occurrence_note(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_get_occurrence_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.get_occurrence_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_get_occurrence_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/occurrences/sample2"} - - # 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 - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_occurrence_note(**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/*/occurrences/*}/notes" % client.transport._host, - args[1], - ) - - -def test_get_occurrence_note_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_occurrence_note( - grafeas.GetOccurrenceNoteRequest(), - name="name_value", - ) - - -def test_get_note_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_note] = mock_rpc - - request = {} - client.get_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_note_rest_required_fields(request_type=grafeas.GetNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_note._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_note._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_note(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_get_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.get_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_get_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/notes/sample2"} - - # 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 - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_note(**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/*/notes/*}" % client.transport._host, args[1] - ) - - -def test_get_note_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_note( - grafeas.GetNoteRequest(), - name="name_value", - ) - - -def test_list_notes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_notes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.list_notes] = mock_rpc - - request = {} - client.list_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_notes_rest_required_fields(request_type=grafeas.ListNotesRequest): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_notes._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_notes._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.ListNotesResponse() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.ListNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_notes(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_list_notes_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_notes._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) - - -def test_list_notes_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.ListNotesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - filter="filter_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.ListNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_notes(**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/*}/notes" % client.transport._host, args[1] - ) - - -def test_list_notes_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_notes( - grafeas.ListNotesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_list_notes_rest_pager(transport: str = "rest"): - client = GrafeasClient( - 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 = ( - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - grafeas.Note(), - ], - next_page_token="abc", - ), - grafeas.ListNotesResponse( - notes=[], - next_page_token="def", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - ], - next_page_token="ghi", - ), - grafeas.ListNotesResponse( - notes=[ - grafeas.Note(), - grafeas.Note(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(grafeas.ListNotesResponse.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"} - - pager = client.list_notes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Note) for i in results) - - pages = list(client.list_notes(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_note_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.delete_note] = mock_rpc - - request = {} - client.delete_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_note_rest_required_fields(request_type=grafeas.DeleteNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_note._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_note._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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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 = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_note(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_delete_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.delete_note._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_delete_note_rest_flattened(): - client = GrafeasClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/notes/sample2"} - - # 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 = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_note(**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/*/notes/*}" % client.transport._host, args[1] - ) - - -def test_delete_note_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_note( - grafeas.DeleteNoteRequest(), - name="name_value", - ) - - -def test_create_note_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_note] = mock_rpc - - request = {} - client.create_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_note_rest_required_fields(request_type=grafeas.CreateNoteRequest): - transport_class = transports.GrafeasRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["note_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - assert "noteId" not in jsonified_request - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_note._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "noteId" in jsonified_request - assert jsonified_request["noteId"] == request_init["note_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["noteId"] = "note_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_note._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("note_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 "noteId" in jsonified_request - assert jsonified_request["noteId"] == "note_id_value" - - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_note(request) - - expected_params = [ - ( - "noteId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_create_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.create_note._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("noteId",)) - & set( - ( - "parent", - "noteId", - "note", - ) - ) - ) - - -def test_create_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - note_id="note_id_value", - note=grafeas.Note(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_note(**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/*}/notes" % client.transport._host, args[1] - ) - - -def test_create_note_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_note( - grafeas.CreateNoteRequest(), - parent="parent_value", - note_id="note_id_value", - note=grafeas.Note(name="name_value"), - ) - - -def test_batch_create_notes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.batch_create_notes in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_create_notes - ] = mock_rpc - - request = {} - client.batch_create_notes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_notes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_batch_create_notes_rest_required_fields( - request_type=grafeas.BatchCreateNotesRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_create_notes._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() - ).batch_create_notes._get_unset_required_fields(jsonified_request) - 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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.BatchCreateNotesResponse() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.BatchCreateNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.batch_create_notes(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_batch_create_notes_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.batch_create_notes._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "notes", - ) - ) - ) - - -def test_batch_create_notes_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.BatchCreateNotesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - notes={"key_value": grafeas.Note(name="name_value")}, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.BatchCreateNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.batch_create_notes(**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/*}/notes:batchCreate" % client.transport._host, - args[1], - ) - - -def test_batch_create_notes_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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.batch_create_notes( - grafeas.BatchCreateNotesRequest(), - parent="parent_value", - notes={"key_value": grafeas.Note(name="name_value")}, - ) - - -def test_update_note_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_note in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_note] = mock_rpc - - request = {} - client.update_note(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_note(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_note_rest_required_fields(request_type=grafeas.UpdateNoteRequest): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_note._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() - ).update_note._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) - 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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.Note() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_note(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_update_note_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.update_note._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "name", - "note", - ) - ) - ) - - -def test_update_note_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.Note() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/notes/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - note=grafeas.Note(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 - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_note(**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/*/notes/*}" % client.transport._host, args[1] - ) - - -def test_update_note_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_note( - grafeas.UpdateNoteRequest(), - name="name_value", - note=grafeas.Note(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_list_note_occurrences_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_note_occurrences - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_note_occurrences - ] = mock_rpc - - request = {} - client.list_note_occurrences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_note_occurrences(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_note_occurrences_rest_required_fields( - request_type=grafeas.ListNoteOccurrencesRequest, -): - transport_class = transports.GrafeasRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_note_occurrences._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() - ).list_note_occurrences._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - ) - ) - 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 = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = grafeas.ListNoteOccurrencesResponse() - # 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 - - # Convert return value to protobuf type - return_value = grafeas.ListNoteOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_note_occurrences(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_list_note_occurrences_rest_unset_required_fields(): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_note_occurrences._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set(("name",)) - ) - - -def test_list_note_occurrences_rest_flattened(): - client = GrafeasClient( - 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 = grafeas.ListNoteOccurrencesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/notes/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - filter="filter_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = grafeas.ListNoteOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_note_occurrences(**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/*/notes/*}/occurrences" % client.transport._host, - args[1], - ) - - -def test_list_note_occurrences_rest_flattened_error(transport: str = "rest"): - client = GrafeasClient( - 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_note_occurrences( - grafeas.ListNoteOccurrencesRequest(), - name="name_value", - filter="filter_value", - ) - - -def test_list_note_occurrences_rest_pager(transport: str = "rest"): - client = GrafeasClient( - 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 = ( - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - next_page_token="abc", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[], - next_page_token="def", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - ], - next_page_token="ghi", - ), - grafeas.ListNoteOccurrencesResponse( - occurrences=[ - grafeas.Occurrence(), - grafeas.Occurrence(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - grafeas.ListNoteOccurrencesResponse.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 = {"name": "projects/sample1/notes/sample2"} - - pager = client.list_note_occurrences(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, grafeas.Occurrence) for i in results) - - pages = list(client.list_note_occurrences(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = GrafeasClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GrafeasGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.GrafeasGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - transports.GrafeasRestTransport, - ], -) -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_transport_kind_grpc(): - transport = GrafeasClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - call.return_value = grafeas.Occurrence() - client.get_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_occurrences_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - call.return_value = grafeas.ListOccurrencesResponse() - client.list_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListOccurrencesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - call.return_value = None - client.delete_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - call.return_value = grafeas.Occurrence() - client.create_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_occurrences_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - call.return_value = grafeas.BatchCreateOccurrencesResponse() - client.batch_create_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateOccurrencesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_occurrence_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - call.return_value = grafeas.Occurrence() - client.update_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_occurrence_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - call.return_value = grafeas.Note() - client.get_occurrence_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - call.return_value = grafeas.Note() - client.get_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_notes_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - call.return_value = grafeas.ListNotesResponse() - client.list_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNotesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - call.return_value = None - client.delete_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - call.return_value = grafeas.Note() - client.create_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_notes_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - call.return_value = grafeas.BatchCreateNotesResponse() - client.batch_create_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateNotesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_note_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - call.return_value = grafeas.Note() - client.update_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_note_occurrences_empty_call_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - call.return_value = grafeas.ListNoteOccurrencesResponse() - client.list_note_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNoteOccurrencesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = GrafeasAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - ) - await client.get_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_occurrences_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListOccurrencesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListOccurrencesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - ) - await client.create_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_batch_create_occurrences_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateOccurrencesResponse() - ) - await client.batch_create_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateOccurrencesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_occurrence_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - ) - await client.update_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_occurrence_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - await client.get_occurrence_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - await client.get_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_notes_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNotesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNotesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - await client.create_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_batch_create_notes_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.BatchCreateNotesResponse() - ) - await client.batch_create_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateNotesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_note_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - ) - await client.update_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_note_occurrences_empty_call_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grafeas.ListNoteOccurrencesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_note_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNoteOccurrencesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = GrafeasClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_occurrence_rest_bad_request(request_type=grafeas.GetOccurrenceRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_occurrence(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.GetOccurrenceRequest, - dict, - ], -) -def test_get_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_occurrence(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_get_occurrence" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_get_occurrence_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_get_occurrence" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.GetOccurrenceRequest.pb(grafeas.GetOccurrenceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Occurrence.to_json(grafeas.Occurrence()) - req.return_value.content = return_value - - request = grafeas.GetOccurrenceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Occurrence() - post_with_metadata.return_value = grafeas.Occurrence(), metadata - - client.get_occurrence( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_occurrences_rest_bad_request(request_type=grafeas.ListOccurrencesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_occurrences(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.ListOccurrencesRequest, - dict, - ], -) -def test_list_occurrences_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "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 = grafeas.ListOccurrencesResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.ListOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_occurrences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOccurrencesPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_occurrences_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_list_occurrences" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_list_occurrences_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_list_occurrences" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.ListOccurrencesRequest.pb(grafeas.ListOccurrencesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.ListOccurrencesResponse.to_json( - grafeas.ListOccurrencesResponse() - ) - req.return_value.content = return_value - - request = grafeas.ListOccurrencesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.ListOccurrencesResponse() - post_with_metadata.return_value = grafeas.ListOccurrencesResponse(), metadata - - client.list_occurrences( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_occurrence_rest_bad_request( - request_type=grafeas.DeleteOccurrenceRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_occurrence(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.DeleteOccurrenceRequest, - dict, - ], -) -def test_delete_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_occurrence(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "pre_delete_occurrence" - ) as pre: - pre.assert_not_called() - pb_message = grafeas.DeleteOccurrenceRequest.pb( - grafeas.DeleteOccurrenceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = grafeas.DeleteOccurrenceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_occurrence( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_create_occurrence_rest_bad_request( - request_type=grafeas.CreateOccurrenceRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_occurrence(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.CreateOccurrenceRequest, - dict, - ], -) -def test_create_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - request_init["occurrence"] = { - "name": "name_value", - "resource_uri": "resource_uri_value", - "note_name": "note_name_value", - "kind": 1, - "remediation": "remediation_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "vulnerability": { - "type_": "type__value", - "severity": 1, - "cvss_score": 0.1082, - "cvssv3": { - "base_score": 0.1046, - "exploitability_score": 0.21580000000000002, - "impact_score": 0.1273, - "attack_vector": 1, - "attack_complexity": 1, - "authentication": 1, - "privileges_required": 1, - "user_interaction": 1, - "scope": 1, - "confidentiality_impact": 1, - "integrity_impact": 1, - "availability_impact": 1, - }, - "package_issue": [ - { - "affected_cpe_uri": "affected_cpe_uri_value", - "affected_package": "affected_package_value", - "affected_version": { - "epoch": 527, - "name": "name_value", - "revision": "revision_value", - "inclusive": True, - "kind": 1, - "full_name": "full_name_value", - }, - "fixed_cpe_uri": "fixed_cpe_uri_value", - "fixed_package": "fixed_package_value", - "fixed_version": {}, - "fix_available": True, - "package_type": "package_type_value", - "effective_severity": 1, - "file_location": [ - { - "file_path": "file_path_value", - "layer_details": { - "index": 536, - "diff_id": "diff_id_value", - "chain_id": "chain_id_value", - "command": "command_value", - "base_images": [ - { - "name": "name_value", - "repository": "repository_value", - "layer_count": 1189, - } - ], - }, - } - ], - } - ], - "short_description": "short_description_value", - "long_description": "long_description_value", - "related_urls": [{"url": "url_value", "label": "label_value"}], - "effective_severity": 1, - "fix_available": True, - "cvss_version": 1, - "cvss_v2": {}, - "vex_assessment": { - "cve": "cve_value", - "vulnerability_id": "vulnerability_id_value", - "related_uris": {}, - "note_name": "note_name_value", - "state": 1, - "impacts": ["impacts_value1", "impacts_value2"], - "remediations": [ - { - "remediation_type": 1, - "details": "details_value", - "remediation_uri": {}, - } - ], - "justification": {"justification_type": 1, "details": "details_value"}, - }, - "extra_details": "extra_details_value", - }, - "build": { - "provenance": { - "id": "id_value", - "project_id": "project_id_value", - "commands": [ - { - "name": "name_value", - "env": ["env_value1", "env_value2"], - "args": ["args_value1", "args_value2"], - "dir_": "dir__value", - "id": "id_value", - "wait_for": ["wait_for_value1", "wait_for_value2"], - } - ], - "built_artifacts": [ - { - "checksum": "checksum_value", - "id": "id_value", - "names": ["names_value1", "names_value2"], - } - ], - "create_time": {}, - "start_time": {}, - "end_time": {}, - "creator": "creator_value", - "logs_uri": "logs_uri_value", - "source_provenance": { - "artifact_storage_source_uri": "artifact_storage_source_uri_value", - "file_hashes": {}, - "context": { - "cloud_repo": { - "repo_id": { - "project_repo_id": { - "project_id": "project_id_value", - "repo_name": "repo_name_value", - }, - "uid": "uid_value", - }, - "revision_id": "revision_id_value", - "alias_context": {"kind": 1, "name": "name_value"}, - }, - "gerrit": { - "host_uri": "host_uri_value", - "gerrit_project": "gerrit_project_value", - "revision_id": "revision_id_value", - "alias_context": {}, - }, - "git": {"url": "url_value", "revision_id": "revision_id_value"}, - "labels": {}, - }, - "additional_contexts": {}, - }, - "trigger_id": "trigger_id_value", - "build_options": {}, - "builder_version": "builder_version_value", - }, - "provenance_bytes": "provenance_bytes_value", - "intoto_provenance": { - "builder_config": {"id": "id_value"}, - "recipe": { - "type_": "type__value", - "defined_in_material": 1971, - "entry_point": "entry_point_value", - "arguments": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - "environment": {}, - }, - "metadata": { - "build_invocation_id": "build_invocation_id_value", - "build_started_on": {}, - "build_finished_on": {}, - "completeness": { - "arguments": True, - "environment": True, - "materials": True, - }, - "reproducible": True, - }, - "materials": ["materials_value1", "materials_value2"], - }, - "intoto_statement": { - "type_": "type__value", - "subject": [{"name": "name_value", "digest": {}}], - "predicate_type": "predicate_type_value", - "provenance": {}, - "slsa_provenance": { - "builder": {"id": "id_value"}, - "recipe": { - "type_": "type__value", - "defined_in_material": 1971, - "entry_point": "entry_point_value", - "arguments": {}, - "environment": {}, - }, - "metadata": { - "build_invocation_id": "build_invocation_id_value", - "build_started_on": {}, - "build_finished_on": {}, - "completeness": { - "arguments": True, - "environment": True, - "materials": True, - }, - "reproducible": True, - }, - "materials": [{"uri": "uri_value", "digest": {}}], - }, - "slsa_provenance_zero_two": { - "builder": {"id": "id_value"}, - "build_type": "build_type_value", - "invocation": { - "config_source": { - "uri": "uri_value", - "digest": {}, - "entry_point": "entry_point_value", - }, - "parameters": {"fields": {}}, - "environment": {}, - }, - "build_config": {}, - "metadata": { - "build_invocation_id": "build_invocation_id_value", - "build_started_on": {}, - "build_finished_on": {}, - "completeness": { - "parameters": True, - "environment": True, - "materials": True, - }, - "reproducible": True, - }, - "materials": [{"uri": "uri_value", "digest": {}}], - }, - }, - "in_toto_slsa_provenance_v1": { - "type_": "type__value", - "subject": {}, - "predicate_type": "predicate_type_value", - "predicate": { - "build_definition": { - "build_type": "build_type_value", - "external_parameters": {}, - "internal_parameters": {}, - "resolved_dependencies": [ - { - "name": "name_value", - "uri": "uri_value", - "digest": {}, - "content": b"content_blob", - "download_location": "download_location_value", - "media_type": "media_type_value", - "annotations": {}, - } - ], - }, - "run_details": { - "builder": { - "id": "id_value", - "version": {}, - "builder_dependencies": {}, - }, - "metadata": { - "invocation_id": "invocation_id_value", - "started_on": {}, - "finished_on": {}, - }, - "byproducts": {}, - }, - }, - }, - }, - "image": { - "fingerprint": { - "v1_name": "v1_name_value", - "v2_blob": ["v2_blob_value1", "v2_blob_value2"], - "v2_name": "v2_name_value", - }, - "distance": 843, - "layer_info": [ - {"directive": "directive_value", "arguments": "arguments_value"} - ], - "base_resource_url": "base_resource_url_value", - }, - "package": { - "name": "name_value", - "location": [ - {"cpe_uri": "cpe_uri_value", "version": {}, "path": "path_value"} - ], - "package_type": "package_type_value", - "cpe_uri": "cpe_uri_value", - "architecture": 1, - "license_": { - "expression": "expression_value", - "comments": "comments_value", - }, - "version": {}, - }, - "deployment": { - "user_email": "user_email_value", - "deploy_time": {}, - "undeploy_time": {}, - "config": "config_value", - "address": "address_value", - "resource_uri": ["resource_uri_value1", "resource_uri_value2"], - "platform": 1, - }, - "discovery": { - "continuous_analysis": 1, - "analysis_status": 1, - "analysis_completed": { - "analysis_type": ["analysis_type_value1", "analysis_type_value2"] - }, - "analysis_error": [ - {"code": 411, "message": "message_value", "details": {}} - ], - "analysis_status_error": {}, - "cpe": "cpe_value", - "last_scan_time": {}, - "archive_time": {}, - "sbom_status": {"sbom_state": 1, "error": "error_value"}, - "vulnerability_attestation": { - "last_attempt_time": {}, - "state": 1, - "error": "error_value", - }, - }, - "attestation": { - "serialized_payload": b"serialized_payload_blob", - "signatures": [ - {"signature": b"signature_blob", "public_key_id": "public_key_id_value"} - ], - "jwts": [{"compact_jwt": "compact_jwt_value"}], - }, - "upgrade": { - "package": "package_value", - "parsed_version": {}, - "distribution": { - "cpe_uri": "cpe_uri_value", - "classification": "classification_value", - "severity": "severity_value", - "cve": ["cve_value1", "cve_value2"], - }, - "windows_update": { - "identity": {"update_id": "update_id_value", "revision": 879}, - "title": "title_value", - "description": "description_value", - "categories": [ - {"category_id": "category_id_value", "name": "name_value"} - ], - "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], - "support_url": "support_url_value", - "last_published_timestamp": {}, - }, - }, - "compliance": { - "non_compliant_files": [ - { - "path": "path_value", - "display_command": "display_command_value", - "reason": "reason_value", - } - ], - "non_compliance_reason": "non_compliance_reason_value", - "version": { - "cpe_uri": "cpe_uri_value", - "benchmark_document": "benchmark_document_value", - "version": "version_value", - }, - }, - "dsse_attestation": { - "envelope": { - "payload": b"payload_blob", - "payload_type": "payload_type_value", - "signatures": [{"sig": b"sig_blob", "keyid": "keyid_value"}], - }, - "statement": {}, - }, - "sbom_reference": { - "payload": { - "type_": "type__value", - "predicate_type": "predicate_type_value", - "subject": {}, - "predicate": { - "referrer_id": "referrer_id_value", - "location": "location_value", - "mime_type": "mime_type_value", - "digest": {}, - }, - }, - "payload_type": "payload_type_value", - "signatures": {}, - }, - "secret": { - "kind": 1, - "locations": [{"file_location": {}}], - "statuses": [{"status": 1, "update_time": {}, "message": "message_value"}], - }, - "envelope": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = grafeas.CreateOccurrenceRequest.meta.fields["occurrence"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["occurrence"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["occurrence"][field])): - del request_init["occurrence"][field][i][subfield] - else: - del request_init["occurrence"][field][subfield] - 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 = grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_occurrence(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_create_occurrence" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_create_occurrence_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_create_occurrence" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.CreateOccurrenceRequest.pb( - grafeas.CreateOccurrenceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Occurrence.to_json(grafeas.Occurrence()) - req.return_value.content = return_value - - request = grafeas.CreateOccurrenceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Occurrence() - post_with_metadata.return_value = grafeas.Occurrence(), metadata - - client.create_occurrence( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_batch_create_occurrences_rest_bad_request( - request_type=grafeas.BatchCreateOccurrencesRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.batch_create_occurrences(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.BatchCreateOccurrencesRequest, - dict, - ], -) -def test_batch_create_occurrences_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "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 = grafeas.BatchCreateOccurrencesResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.BatchCreateOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_create_occurrences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_occurrences_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_batch_create_occurrences" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_batch_create_occurrences_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_batch_create_occurrences" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.BatchCreateOccurrencesRequest.pb( - grafeas.BatchCreateOccurrencesRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.BatchCreateOccurrencesResponse.to_json( - grafeas.BatchCreateOccurrencesResponse() - ) - req.return_value.content = return_value - - request = grafeas.BatchCreateOccurrencesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.BatchCreateOccurrencesResponse() - post_with_metadata.return_value = ( - grafeas.BatchCreateOccurrencesResponse(), - metadata, - ) - - client.batch_create_occurrences( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_occurrence_rest_bad_request( - request_type=grafeas.UpdateOccurrenceRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_occurrence(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.UpdateOccurrenceRequest, - dict, - ], -) -def test_update_occurrence_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/sample2"} - request_init["occurrence"] = { - "name": "name_value", - "resource_uri": "resource_uri_value", - "note_name": "note_name_value", - "kind": 1, - "remediation": "remediation_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "vulnerability": { - "type_": "type__value", - "severity": 1, - "cvss_score": 0.1082, - "cvssv3": { - "base_score": 0.1046, - "exploitability_score": 0.21580000000000002, - "impact_score": 0.1273, - "attack_vector": 1, - "attack_complexity": 1, - "authentication": 1, - "privileges_required": 1, - "user_interaction": 1, - "scope": 1, - "confidentiality_impact": 1, - "integrity_impact": 1, - "availability_impact": 1, - }, - "package_issue": [ - { - "affected_cpe_uri": "affected_cpe_uri_value", - "affected_package": "affected_package_value", - "affected_version": { - "epoch": 527, - "name": "name_value", - "revision": "revision_value", - "inclusive": True, - "kind": 1, - "full_name": "full_name_value", - }, - "fixed_cpe_uri": "fixed_cpe_uri_value", - "fixed_package": "fixed_package_value", - "fixed_version": {}, - "fix_available": True, - "package_type": "package_type_value", - "effective_severity": 1, - "file_location": [ - { - "file_path": "file_path_value", - "layer_details": { - "index": 536, - "diff_id": "diff_id_value", - "chain_id": "chain_id_value", - "command": "command_value", - "base_images": [ - { - "name": "name_value", - "repository": "repository_value", - "layer_count": 1189, - } - ], - }, - } - ], - } - ], - "short_description": "short_description_value", - "long_description": "long_description_value", - "related_urls": [{"url": "url_value", "label": "label_value"}], - "effective_severity": 1, - "fix_available": True, - "cvss_version": 1, - "cvss_v2": {}, - "vex_assessment": { - "cve": "cve_value", - "vulnerability_id": "vulnerability_id_value", - "related_uris": {}, - "note_name": "note_name_value", - "state": 1, - "impacts": ["impacts_value1", "impacts_value2"], - "remediations": [ - { - "remediation_type": 1, - "details": "details_value", - "remediation_uri": {}, - } - ], - "justification": {"justification_type": 1, "details": "details_value"}, - }, - "extra_details": "extra_details_value", - }, - "build": { - "provenance": { - "id": "id_value", - "project_id": "project_id_value", - "commands": [ - { - "name": "name_value", - "env": ["env_value1", "env_value2"], - "args": ["args_value1", "args_value2"], - "dir_": "dir__value", - "id": "id_value", - "wait_for": ["wait_for_value1", "wait_for_value2"], - } - ], - "built_artifacts": [ - { - "checksum": "checksum_value", - "id": "id_value", - "names": ["names_value1", "names_value2"], - } - ], - "create_time": {}, - "start_time": {}, - "end_time": {}, - "creator": "creator_value", - "logs_uri": "logs_uri_value", - "source_provenance": { - "artifact_storage_source_uri": "artifact_storage_source_uri_value", - "file_hashes": {}, - "context": { - "cloud_repo": { - "repo_id": { - "project_repo_id": { - "project_id": "project_id_value", - "repo_name": "repo_name_value", - }, - "uid": "uid_value", - }, - "revision_id": "revision_id_value", - "alias_context": {"kind": 1, "name": "name_value"}, - }, - "gerrit": { - "host_uri": "host_uri_value", - "gerrit_project": "gerrit_project_value", - "revision_id": "revision_id_value", - "alias_context": {}, - }, - "git": {"url": "url_value", "revision_id": "revision_id_value"}, - "labels": {}, - }, - "additional_contexts": {}, - }, - "trigger_id": "trigger_id_value", - "build_options": {}, - "builder_version": "builder_version_value", - }, - "provenance_bytes": "provenance_bytes_value", - "intoto_provenance": { - "builder_config": {"id": "id_value"}, - "recipe": { - "type_": "type__value", - "defined_in_material": 1971, - "entry_point": "entry_point_value", - "arguments": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - "environment": {}, - }, - "metadata": { - "build_invocation_id": "build_invocation_id_value", - "build_started_on": {}, - "build_finished_on": {}, - "completeness": { - "arguments": True, - "environment": True, - "materials": True, - }, - "reproducible": True, - }, - "materials": ["materials_value1", "materials_value2"], - }, - "intoto_statement": { - "type_": "type__value", - "subject": [{"name": "name_value", "digest": {}}], - "predicate_type": "predicate_type_value", - "provenance": {}, - "slsa_provenance": { - "builder": {"id": "id_value"}, - "recipe": { - "type_": "type__value", - "defined_in_material": 1971, - "entry_point": "entry_point_value", - "arguments": {}, - "environment": {}, - }, - "metadata": { - "build_invocation_id": "build_invocation_id_value", - "build_started_on": {}, - "build_finished_on": {}, - "completeness": { - "arguments": True, - "environment": True, - "materials": True, - }, - "reproducible": True, - }, - "materials": [{"uri": "uri_value", "digest": {}}], - }, - "slsa_provenance_zero_two": { - "builder": {"id": "id_value"}, - "build_type": "build_type_value", - "invocation": { - "config_source": { - "uri": "uri_value", - "digest": {}, - "entry_point": "entry_point_value", - }, - "parameters": {"fields": {}}, - "environment": {}, - }, - "build_config": {}, - "metadata": { - "build_invocation_id": "build_invocation_id_value", - "build_started_on": {}, - "build_finished_on": {}, - "completeness": { - "parameters": True, - "environment": True, - "materials": True, - }, - "reproducible": True, - }, - "materials": [{"uri": "uri_value", "digest": {}}], - }, - }, - "in_toto_slsa_provenance_v1": { - "type_": "type__value", - "subject": {}, - "predicate_type": "predicate_type_value", - "predicate": { - "build_definition": { - "build_type": "build_type_value", - "external_parameters": {}, - "internal_parameters": {}, - "resolved_dependencies": [ - { - "name": "name_value", - "uri": "uri_value", - "digest": {}, - "content": b"content_blob", - "download_location": "download_location_value", - "media_type": "media_type_value", - "annotations": {}, - } - ], - }, - "run_details": { - "builder": { - "id": "id_value", - "version": {}, - "builder_dependencies": {}, - }, - "metadata": { - "invocation_id": "invocation_id_value", - "started_on": {}, - "finished_on": {}, - }, - "byproducts": {}, - }, - }, - }, - }, - "image": { - "fingerprint": { - "v1_name": "v1_name_value", - "v2_blob": ["v2_blob_value1", "v2_blob_value2"], - "v2_name": "v2_name_value", - }, - "distance": 843, - "layer_info": [ - {"directive": "directive_value", "arguments": "arguments_value"} - ], - "base_resource_url": "base_resource_url_value", - }, - "package": { - "name": "name_value", - "location": [ - {"cpe_uri": "cpe_uri_value", "version": {}, "path": "path_value"} - ], - "package_type": "package_type_value", - "cpe_uri": "cpe_uri_value", - "architecture": 1, - "license_": { - "expression": "expression_value", - "comments": "comments_value", - }, - "version": {}, - }, - "deployment": { - "user_email": "user_email_value", - "deploy_time": {}, - "undeploy_time": {}, - "config": "config_value", - "address": "address_value", - "resource_uri": ["resource_uri_value1", "resource_uri_value2"], - "platform": 1, - }, - "discovery": { - "continuous_analysis": 1, - "analysis_status": 1, - "analysis_completed": { - "analysis_type": ["analysis_type_value1", "analysis_type_value2"] - }, - "analysis_error": [ - {"code": 411, "message": "message_value", "details": {}} - ], - "analysis_status_error": {}, - "cpe": "cpe_value", - "last_scan_time": {}, - "archive_time": {}, - "sbom_status": {"sbom_state": 1, "error": "error_value"}, - "vulnerability_attestation": { - "last_attempt_time": {}, - "state": 1, - "error": "error_value", - }, - }, - "attestation": { - "serialized_payload": b"serialized_payload_blob", - "signatures": [ - {"signature": b"signature_blob", "public_key_id": "public_key_id_value"} - ], - "jwts": [{"compact_jwt": "compact_jwt_value"}], - }, - "upgrade": { - "package": "package_value", - "parsed_version": {}, - "distribution": { - "cpe_uri": "cpe_uri_value", - "classification": "classification_value", - "severity": "severity_value", - "cve": ["cve_value1", "cve_value2"], - }, - "windows_update": { - "identity": {"update_id": "update_id_value", "revision": 879}, - "title": "title_value", - "description": "description_value", - "categories": [ - {"category_id": "category_id_value", "name": "name_value"} - ], - "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], - "support_url": "support_url_value", - "last_published_timestamp": {}, - }, - }, - "compliance": { - "non_compliant_files": [ - { - "path": "path_value", - "display_command": "display_command_value", - "reason": "reason_value", - } - ], - "non_compliance_reason": "non_compliance_reason_value", - "version": { - "cpe_uri": "cpe_uri_value", - "benchmark_document": "benchmark_document_value", - "version": "version_value", - }, - }, - "dsse_attestation": { - "envelope": { - "payload": b"payload_blob", - "payload_type": "payload_type_value", - "signatures": [{"sig": b"sig_blob", "keyid": "keyid_value"}], - }, - "statement": {}, - }, - "sbom_reference": { - "payload": { - "type_": "type__value", - "predicate_type": "predicate_type_value", - "subject": {}, - "predicate": { - "referrer_id": "referrer_id_value", - "location": "location_value", - "mime_type": "mime_type_value", - "digest": {}, - }, - }, - "payload_type": "payload_type_value", - "signatures": {}, - }, - "secret": { - "kind": 1, - "locations": [{"file_location": {}}], - "statuses": [{"status": 1, "update_time": {}, "message": "message_value"}], - }, - "envelope": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = grafeas.UpdateOccurrenceRequest.meta.fields["occurrence"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["occurrence"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["occurrence"][field])): - del request_init["occurrence"][field][i][subfield] - else: - del request_init["occurrence"][field][subfield] - 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 = grafeas.Occurrence( - name="name_value", - resource_uri="resource_uri_value", - note_name="note_name_value", - kind=common.NoteKind.VULNERABILITY, - remediation="remediation_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Occurrence.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_occurrence(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Occurrence) - assert response.name == "name_value" - assert response.resource_uri == "resource_uri_value" - assert response.note_name == "note_name_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.remediation == "remediation_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_occurrence_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_update_occurrence" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_update_occurrence_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_update_occurrence" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.UpdateOccurrenceRequest.pb( - grafeas.UpdateOccurrenceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Occurrence.to_json(grafeas.Occurrence()) - req.return_value.content = return_value - - request = grafeas.UpdateOccurrenceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Occurrence() - post_with_metadata.return_value = grafeas.Occurrence(), metadata - - client.update_occurrence( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_occurrence_note_rest_bad_request( - request_type=grafeas.GetOccurrenceNoteRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_occurrence_note(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.GetOccurrenceNoteRequest, - dict, - ], -) -def test_get_occurrence_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/occurrences/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 = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_occurrence_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_occurrence_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_get_occurrence_note" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_get_occurrence_note_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_get_occurrence_note" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.GetOccurrenceNoteRequest.pb( - grafeas.GetOccurrenceNoteRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.GetOccurrenceNoteRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - post_with_metadata.return_value = grafeas.Note(), metadata - - client.get_occurrence_note( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_note_rest_bad_request(request_type=grafeas.GetNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_note(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.GetNoteRequest, - dict, - ], -) -def test_get_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_get_note" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_get_note_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_get_note" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.GetNoteRequest.pb(grafeas.GetNoteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.GetNoteRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - post_with_metadata.return_value = grafeas.Note(), metadata - - client.get_note( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_notes_rest_bad_request(request_type=grafeas.ListNotesRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_notes(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.ListNotesRequest, - dict, - ], -) -def test_list_notes_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "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 = grafeas.ListNotesResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.ListNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_notes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotesPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notes_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_list_notes" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_list_notes_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_list_notes" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.ListNotesRequest.pb(grafeas.ListNotesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.ListNotesResponse.to_json(grafeas.ListNotesResponse()) - req.return_value.content = return_value - - request = grafeas.ListNotesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.ListNotesResponse() - post_with_metadata.return_value = grafeas.ListNotesResponse(), metadata - - client.list_notes( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_note_rest_bad_request(request_type=grafeas.DeleteNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_note(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.DeleteNoteRequest, - dict, - ], -) -def test_delete_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_note(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "pre_delete_note" - ) as pre: - pre.assert_not_called() - pb_message = grafeas.DeleteNoteRequest.pb(grafeas.DeleteNoteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = grafeas.DeleteNoteRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_note( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_create_note_rest_bad_request(request_type=grafeas.CreateNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_note(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.CreateNoteRequest, - dict, - ], -) -def test_create_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - request_init["note"] = { - "name": "name_value", - "short_description": "short_description_value", - "long_description": "long_description_value", - "kind": 1, - "related_url": [{"url": "url_value", "label": "label_value"}], - "expiration_time": {"seconds": 751, "nanos": 543}, - "create_time": {}, - "update_time": {}, - "related_note_names": [ - "related_note_names_value1", - "related_note_names_value2", - ], - "vulnerability": { - "cvss_score": 0.1082, - "severity": 1, - "details": [ - { - "severity_name": "severity_name_value", - "description": "description_value", - "package_type": "package_type_value", - "affected_cpe_uri": "affected_cpe_uri_value", - "affected_package": "affected_package_value", - "affected_version_start": { - "epoch": 527, - "name": "name_value", - "revision": "revision_value", - "inclusive": True, - "kind": 1, - "full_name": "full_name_value", - }, - "affected_version_end": {}, - "fixed_cpe_uri": "fixed_cpe_uri_value", - "fixed_package": "fixed_package_value", - "fixed_version": {}, - "is_obsolete": True, - "source_update_time": {}, - "source": "source_value", - "vendor": "vendor_value", - } - ], - "cvss_v3": { - "base_score": 0.1046, - "exploitability_score": 0.21580000000000002, - "impact_score": 0.1273, - "attack_vector": 1, - "attack_complexity": 1, - "privileges_required": 1, - "user_interaction": 1, - "scope": 1, - "confidentiality_impact": 1, - "integrity_impact": 1, - "availability_impact": 1, - }, - "windows_details": [ - { - "cpe_uri": "cpe_uri_value", - "name": "name_value", - "description": "description_value", - "fixing_kbs": [{"name": "name_value", "url": "url_value"}], - } - ], - "source_update_time": {}, - "cvss_version": 1, - "cvss_v2": { - "base_score": 0.1046, - "exploitability_score": 0.21580000000000002, - "impact_score": 0.1273, - "attack_vector": 1, - "attack_complexity": 1, - "authentication": 1, - "privileges_required": 1, - "user_interaction": 1, - "scope": 1, - "confidentiality_impact": 1, - "integrity_impact": 1, - "availability_impact": 1, - }, - }, - "build": {"builder_version": "builder_version_value"}, - "image": { - "resource_url": "resource_url_value", - "fingerprint": { - "v1_name": "v1_name_value", - "v2_blob": ["v2_blob_value1", "v2_blob_value2"], - "v2_name": "v2_name_value", - }, - }, - "package": { - "name": "name_value", - "distribution": [ - { - "cpe_uri": "cpe_uri_value", - "architecture": 1, - "latest_version": {}, - "maintainer": "maintainer_value", - "url": "url_value", - "description": "description_value", - } - ], - "package_type": "package_type_value", - "cpe_uri": "cpe_uri_value", - "architecture": 1, - "version": {}, - "maintainer": "maintainer_value", - "url": "url_value", - "description": "description_value", - "license_": { - "expression": "expression_value", - "comments": "comments_value", - }, - "digest": [{"algo": "algo_value", "digest_bytes": b"digest_bytes_blob"}], - }, - "deployment": {"resource_uri": ["resource_uri_value1", "resource_uri_value2"]}, - "discovery": {"analysis_kind": 1}, - "attestation": {"hint": {"human_readable_name": "human_readable_name_value"}}, - "upgrade": { - "package": "package_value", - "version": {}, - "distributions": [ - { - "cpe_uri": "cpe_uri_value", - "classification": "classification_value", - "severity": "severity_value", - "cve": ["cve_value1", "cve_value2"], - } - ], - "windows_update": { - "identity": {"update_id": "update_id_value", "revision": 879}, - "title": "title_value", - "description": "description_value", - "categories": [ - {"category_id": "category_id_value", "name": "name_value"} - ], - "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], - "support_url": "support_url_value", - "last_published_timestamp": {}, - }, - }, - "compliance": { - "title": "title_value", - "description": "description_value", - "version": [ - { - "cpe_uri": "cpe_uri_value", - "benchmark_document": "benchmark_document_value", - "version": "version_value", - } - ], - "rationale": "rationale_value", - "remediation": "remediation_value", - "cis_benchmark": {"profile_level": 1384, "severity": 1}, - "scan_instructions": b"scan_instructions_blob", - "impact": "impact_value", - }, - "dsse_attestation": { - "hint": {"human_readable_name": "human_readable_name_value"} - }, - "vulnerability_assessment": { - "title": "title_value", - "short_description": "short_description_value", - "long_description": "long_description_value", - "language_code": "language_code_value", - "publisher": { - "name": "name_value", - "issuing_authority": "issuing_authority_value", - "publisher_namespace": "publisher_namespace_value", - }, - "product": { - "name": "name_value", - "id": "id_value", - "generic_uri": "generic_uri_value", - }, - "assessment": { - "cve": "cve_value", - "vulnerability_id": "vulnerability_id_value", - "short_description": "short_description_value", - "long_description": "long_description_value", - "related_uris": {}, - "state": 1, - "impacts": ["impacts_value1", "impacts_value2"], - "justification": {"justification_type": 1, "details": "details_value"}, - "remediations": [ - { - "remediation_type": 1, - "details": "details_value", - "remediation_uri": {}, - } - ], - }, - }, - "sbom_reference": {"format_": "format__value", "version": "version_value"}, - "secret": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = grafeas.CreateNoteRequest.meta.fields["note"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["note"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["note"][field])): - del request_init["note"][field][i][subfield] - else: - del request_init["note"][field][subfield] - 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 = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_create_note" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_create_note_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_create_note" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.CreateNoteRequest.pb(grafeas.CreateNoteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.CreateNoteRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - post_with_metadata.return_value = grafeas.Note(), metadata - - client.create_note( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_batch_create_notes_rest_bad_request( - request_type=grafeas.BatchCreateNotesRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.batch_create_notes(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.BatchCreateNotesRequest, - dict, - ], -) -def test_batch_create_notes_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "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 = grafeas.BatchCreateNotesResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.BatchCreateNotesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_create_notes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.BatchCreateNotesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_notes_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_batch_create_notes" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_batch_create_notes_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_batch_create_notes" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.BatchCreateNotesRequest.pb( - grafeas.BatchCreateNotesRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.BatchCreateNotesResponse.to_json( - grafeas.BatchCreateNotesResponse() - ) - req.return_value.content = return_value - - request = grafeas.BatchCreateNotesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.BatchCreateNotesResponse() - post_with_metadata.return_value = grafeas.BatchCreateNotesResponse(), metadata - - client.batch_create_notes( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_note_rest_bad_request(request_type=grafeas.UpdateNoteRequest): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_note(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.UpdateNoteRequest, - dict, - ], -) -def test_update_note_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/sample2"} - request_init["note"] = { - "name": "name_value", - "short_description": "short_description_value", - "long_description": "long_description_value", - "kind": 1, - "related_url": [{"url": "url_value", "label": "label_value"}], - "expiration_time": {"seconds": 751, "nanos": 543}, - "create_time": {}, - "update_time": {}, - "related_note_names": [ - "related_note_names_value1", - "related_note_names_value2", - ], - "vulnerability": { - "cvss_score": 0.1082, - "severity": 1, - "details": [ - { - "severity_name": "severity_name_value", - "description": "description_value", - "package_type": "package_type_value", - "affected_cpe_uri": "affected_cpe_uri_value", - "affected_package": "affected_package_value", - "affected_version_start": { - "epoch": 527, - "name": "name_value", - "revision": "revision_value", - "inclusive": True, - "kind": 1, - "full_name": "full_name_value", - }, - "affected_version_end": {}, - "fixed_cpe_uri": "fixed_cpe_uri_value", - "fixed_package": "fixed_package_value", - "fixed_version": {}, - "is_obsolete": True, - "source_update_time": {}, - "source": "source_value", - "vendor": "vendor_value", - } - ], - "cvss_v3": { - "base_score": 0.1046, - "exploitability_score": 0.21580000000000002, - "impact_score": 0.1273, - "attack_vector": 1, - "attack_complexity": 1, - "privileges_required": 1, - "user_interaction": 1, - "scope": 1, - "confidentiality_impact": 1, - "integrity_impact": 1, - "availability_impact": 1, - }, - "windows_details": [ - { - "cpe_uri": "cpe_uri_value", - "name": "name_value", - "description": "description_value", - "fixing_kbs": [{"name": "name_value", "url": "url_value"}], - } - ], - "source_update_time": {}, - "cvss_version": 1, - "cvss_v2": { - "base_score": 0.1046, - "exploitability_score": 0.21580000000000002, - "impact_score": 0.1273, - "attack_vector": 1, - "attack_complexity": 1, - "authentication": 1, - "privileges_required": 1, - "user_interaction": 1, - "scope": 1, - "confidentiality_impact": 1, - "integrity_impact": 1, - "availability_impact": 1, - }, - }, - "build": {"builder_version": "builder_version_value"}, - "image": { - "resource_url": "resource_url_value", - "fingerprint": { - "v1_name": "v1_name_value", - "v2_blob": ["v2_blob_value1", "v2_blob_value2"], - "v2_name": "v2_name_value", - }, - }, - "package": { - "name": "name_value", - "distribution": [ - { - "cpe_uri": "cpe_uri_value", - "architecture": 1, - "latest_version": {}, - "maintainer": "maintainer_value", - "url": "url_value", - "description": "description_value", - } - ], - "package_type": "package_type_value", - "cpe_uri": "cpe_uri_value", - "architecture": 1, - "version": {}, - "maintainer": "maintainer_value", - "url": "url_value", - "description": "description_value", - "license_": { - "expression": "expression_value", - "comments": "comments_value", - }, - "digest": [{"algo": "algo_value", "digest_bytes": b"digest_bytes_blob"}], - }, - "deployment": {"resource_uri": ["resource_uri_value1", "resource_uri_value2"]}, - "discovery": {"analysis_kind": 1}, - "attestation": {"hint": {"human_readable_name": "human_readable_name_value"}}, - "upgrade": { - "package": "package_value", - "version": {}, - "distributions": [ - { - "cpe_uri": "cpe_uri_value", - "classification": "classification_value", - "severity": "severity_value", - "cve": ["cve_value1", "cve_value2"], - } - ], - "windows_update": { - "identity": {"update_id": "update_id_value", "revision": 879}, - "title": "title_value", - "description": "description_value", - "categories": [ - {"category_id": "category_id_value", "name": "name_value"} - ], - "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], - "support_url": "support_url_value", - "last_published_timestamp": {}, - }, - }, - "compliance": { - "title": "title_value", - "description": "description_value", - "version": [ - { - "cpe_uri": "cpe_uri_value", - "benchmark_document": "benchmark_document_value", - "version": "version_value", - } - ], - "rationale": "rationale_value", - "remediation": "remediation_value", - "cis_benchmark": {"profile_level": 1384, "severity": 1}, - "scan_instructions": b"scan_instructions_blob", - "impact": "impact_value", - }, - "dsse_attestation": { - "hint": {"human_readable_name": "human_readable_name_value"} - }, - "vulnerability_assessment": { - "title": "title_value", - "short_description": "short_description_value", - "long_description": "long_description_value", - "language_code": "language_code_value", - "publisher": { - "name": "name_value", - "issuing_authority": "issuing_authority_value", - "publisher_namespace": "publisher_namespace_value", - }, - "product": { - "name": "name_value", - "id": "id_value", - "generic_uri": "generic_uri_value", - }, - "assessment": { - "cve": "cve_value", - "vulnerability_id": "vulnerability_id_value", - "short_description": "short_description_value", - "long_description": "long_description_value", - "related_uris": {}, - "state": 1, - "impacts": ["impacts_value1", "impacts_value2"], - "justification": {"justification_type": 1, "details": "details_value"}, - "remediations": [ - { - "remediation_type": 1, - "details": "details_value", - "remediation_uri": {}, - } - ], - }, - }, - "sbom_reference": {"format_": "format__value", "version": "version_value"}, - "secret": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = grafeas.UpdateNoteRequest.meta.fields["note"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["note"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["note"][field])): - del request_init["note"][field][i][subfield] - else: - del request_init["note"][field][subfield] - 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 = grafeas.Note( - name="name_value", - short_description="short_description_value", - long_description="long_description_value", - kind=common.NoteKind.VULNERABILITY, - related_note_names=["related_note_names_value"], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.Note.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_note(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, grafeas.Note) - assert response.name == "name_value" - assert response.short_description == "short_description_value" - assert response.long_description == "long_description_value" - assert response.kind == common.NoteKind.VULNERABILITY - assert response.related_note_names == ["related_note_names_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_note_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_update_note" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_update_note_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_update_note" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.UpdateNoteRequest.pb(grafeas.UpdateNoteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.Note.to_json(grafeas.Note()) - req.return_value.content = return_value - - request = grafeas.UpdateNoteRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.Note() - post_with_metadata.return_value = grafeas.Note(), metadata - - client.update_note( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_note_occurrences_rest_bad_request( - request_type=grafeas.ListNoteOccurrencesRequest, -): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_note_occurrences(request) - - -@pytest.mark.parametrize( - "request_type", - [ - grafeas.ListNoteOccurrencesRequest, - dict, - ], -) -def test_list_note_occurrences_rest_call_success(request_type): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/notes/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 = grafeas.ListNoteOccurrencesResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = grafeas.ListNoteOccurrencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_note_occurrences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNoteOccurrencesPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_note_occurrences_rest_interceptors(null_interceptor): - transport = transports.GrafeasRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), - ) - client = GrafeasClient(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.GrafeasRestInterceptor, "post_list_note_occurrences" - ) as post, mock.patch.object( - transports.GrafeasRestInterceptor, "post_list_note_occurrences_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GrafeasRestInterceptor, "pre_list_note_occurrences" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = grafeas.ListNoteOccurrencesRequest.pb( - grafeas.ListNoteOccurrencesRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = grafeas.ListNoteOccurrencesResponse.to_json( - grafeas.ListNoteOccurrencesResponse() - ) - req.return_value.content = return_value - - request = grafeas.ListNoteOccurrencesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = grafeas.ListNoteOccurrencesResponse() - post_with_metadata.return_value = ( - grafeas.ListNoteOccurrencesResponse(), - metadata, - ) - - client.list_note_occurrences( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_initialize_client_w_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: - client.get_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_occurrences_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: - client.list_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListOccurrencesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_occurrence), "__call__" - ) as call: - client.delete_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_occurrence), "__call__" - ) as call: - client.create_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_occurrences_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_occurrences), "__call__" - ) as call: - client.batch_create_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateOccurrencesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_occurrence_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_occurrence), "__call__" - ) as call: - client.update_occurrence(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateOccurrenceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_occurrence_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_occurrence_note), "__call__" - ) as call: - client.get_occurrence_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetOccurrenceNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_note), "__call__") as call: - client.get_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.GetNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_notes_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_notes), "__call__") as call: - client.list_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNotesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_note), "__call__") as call: - client.delete_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.DeleteNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_note), "__call__") as call: - client.create_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.CreateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_batch_create_notes_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_notes), "__call__" - ) as call: - client.batch_create_notes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.BatchCreateNotesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_note_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_note), "__call__") as call: - client.update_note(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.UpdateNoteRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_note_occurrences_empty_call_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_note_occurrences), "__call__" - ) as call: - client.list_note_occurrences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = grafeas.ListNoteOccurrencesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.GrafeasGrpcTransport, - ) - - -def test_grafeas_base_transport(): - # Instantiate the base transport. - with mock.patch( - "grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.GrafeasTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "get_occurrence", - "list_occurrences", - "delete_occurrence", - "create_occurrence", - "batch_create_occurrences", - "update_occurrence", - "get_occurrence_note", - "get_note", - "list_notes", - "delete_note", - "create_note", - "batch_create_notes", - "update_note", - "list_note_occurrences", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_grafeas_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( - "grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=(), - quota_project_id="octopus", - ) - - -def test_grafeas_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( - "grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GrafeasTransport() - adc.assert_called_once() - - -def test_grafeas_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) - GrafeasClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=(), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - ], -) -def test_grafeas_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=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GrafeasGrpcTransport, - transports.GrafeasGrpcAsyncIOTransport, - transports.GrafeasRestTransport, - ], -) -def test_grafeas_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.GrafeasGrpcTransport, grpc_helpers), - (transports.GrafeasGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_grafeas_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( - ":443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=(), - scopes=["1", "2"], - default_host="", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class", - [transports.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport], -) -def test_grafeas_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_grafeas_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.GrafeasRestTransport( - 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_grafeas_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GrafeasGrpcTransport( - 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_grafeas_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GrafeasGrpcAsyncIOTransport( - 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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport], -) -def test_grafeas_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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport], -) -def test_grafeas_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_note_path(): - project = "squid" - note = "clam" - expected = "projects/{project}/notes/{note}".format( - project=project, - note=note, - ) - actual = GrafeasClient.note_path(project, note) - assert expected == actual - - -def test_parse_note_path(): - expected = { - "project": "whelk", - "note": "octopus", - } - path = GrafeasClient.note_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_note_path(path) - assert expected == actual - - -def test_occurrence_path(): - project = "oyster" - occurrence = "nudibranch" - expected = "projects/{project}/occurrences/{occurrence}".format( - project=project, - occurrence=occurrence, - ) - actual = GrafeasClient.occurrence_path(project, occurrence) - assert expected == actual - - -def test_parse_occurrence_path(): - expected = { - "project": "cuttlefish", - "occurrence": "mussel", - } - path = GrafeasClient.occurrence_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_occurrence_path(path) - assert expected == actual - - -def test_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, - ) - actual = GrafeasClient.project_path(project) - assert expected == actual - - -def test_parse_project_path(): - expected = { - "project": "nautilus", - } - path = GrafeasClient.project_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_project_path(path) - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = GrafeasClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = GrafeasClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = GrafeasClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = GrafeasClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = GrafeasClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = GrafeasClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format( - project=project, - ) - actual = GrafeasClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = GrafeasClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = GrafeasClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = GrafeasClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = GrafeasClient.parse_common_location_path(path) - assert expected == actual - - -def test_transport_close_grpc(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = GrafeasAsyncClient( - credentials=async_anonymous_credentials(), 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_transport_close_rest(): - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - "rest", - "grpc", - ] - for transport in transports: - client = GrafeasClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() From 873435d7d78accee23fa5a8e17cb34800282ac94 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Mon, 10 Nov 2025 20:37:13 +0000 Subject: [PATCH 2/3] fix generation for google-cloud-access-context-manager,google-cloud-audit-log,grafeas,grpc-google-iam-v1 --- .librarian/state.yaml | 25 ++- .../docs/README.rst | 198 +++++++++++++++++- .../google-cloud-audit-log/docs/README.rst | 198 +++++++++++++++++- packages/grpc-google-iam-v1/docs/README.rst | 198 +++++++++++++++++- 4 files changed, 608 insertions(+), 11 deletions(-) mode change 120000 => 100644 packages/google-cloud-access-context-manager/docs/README.rst mode change 120000 => 100644 packages/google-cloud-audit-log/docs/README.rst mode change 120000 => 100644 packages/grpc-google-iam-v1/docs/README.rst diff --git a/.librarian/state.yaml b/.librarian/state.yaml index 3441e6041b87..c8f1c6f1dcc2 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -272,7 +272,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-access-context-manager version: 0.3.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: e8365a7f88fabe8717cb8322b8ce784b03b6daea apis: - path: google/identity/accesscontextmanager/v1 service_config: accesscontextmanager_v1.yaml @@ -282,7 +282,10 @@ libraries: - packages/google-cloud-access-context-manager preserve_regex: [] remove_regex: - - ^packages/google-cloud-access-context-manager/google/.*/.*_pb2\.(?:py|pyi)$/ + - ^packages/google-cloud-access-context-manager/google/.*/.*(?:\.proto|_pb2\.(?:py|pyi))$ + - .repo-metadata.json + - README.rst + - docs/summary_overview.md tag_format: '{id}-v{version}' - id: google-cloud-advisorynotifications version: 0.4.0 @@ -566,7 +569,10 @@ libraries: - packages/google-cloud-audit-log preserve_regex: [] remove_regex: - - ^packages/google-cloud-audit-log/google/.*/.*_pb2\.(?:py|pyi)$/ + - ^packages/google-cloud-audit-log/google/.*/.*(?:\.proto|_pb2\.(?:py|pyi))$ + - .repo-metadata.json + - README.rst + - docs/summary_overview.md tag_format: '{id}-v{version}' - id: google-cloud-automl version: 2.17.0 @@ -4493,7 +4499,7 @@ libraries: tag_format: '{id}-v{version}' - id: grafeas version: 1.16.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: e8365a7f88fabe8717cb8322b8ce784b03b6daea apis: - path: grafeas/v1 service_config: grafeas_v1.yaml @@ -4506,15 +4512,15 @@ libraries: - scripts/client-post-processing - samples/snippets/README.rst - tests/system - - grafeas/grafeas.py - - grafeas/grafeas/__init__.py + - grafeas/grafeas\.py + - ^packages/grafeas/grafeas/__init__.py - grafeas/grafeas/grafeas_v1/types.py remove_regex: - packages/grafeas tag_format: '{id}-v{version}' - id: grpc-google-iam-v1 version: 0.14.2 - last_generated_commit: 55319b058f8a0e46bbeeff30e374e4b1f081f494 + last_generated_commit: e8365a7f88fabe8717cb8322b8ce784b03b6daea apis: - path: google/iam/v1 service_config: iam_meta_api.yaml @@ -4522,5 +4528,8 @@ libraries: - packages/grpc-google-iam-v1/ preserve_regex: [] remove_regex: - - ^packages/grpc-google-iam-v1/google/.*/.*_pb2\.(?:py|pyi)$/ + - ^packages/grpc-google-iam-v1/google/iam/v1/[^/]*(?:\.proto|_pb2\.(?:py|pyi))$ + - .repo-metadata.json + - README.rst + - docs/summary_overview.md tag_format: '{id}-v{version}' diff --git a/packages/google-cloud-access-context-manager/docs/README.rst b/packages/google-cloud-access-context-manager/docs/README.rst deleted file mode 120000 index 89a0106941ff..000000000000 --- a/packages/google-cloud-access-context-manager/docs/README.rst +++ /dev/null @@ -1 +0,0 @@ -../README.rst \ No newline at end of file diff --git a/packages/google-cloud-access-context-manager/docs/README.rst b/packages/google-cloud-access-context-manager/docs/README.rst new file mode 100644 index 000000000000..5fa525df1a41 --- /dev/null +++ b/packages/google-cloud-access-context-manager/docs/README.rst @@ -0,0 +1,197 @@ +Python Client for Access Context Manager +======================================== + +|preview| |pypi| |versions| + +`Access Context Manager`_: + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-access-context-manager.svg + :target: https://pypi.org/project/google-cloud-access-context-manager/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-access-context-manager.svg + :target: https://pypi.org/project/google-cloud-access-context-manager/ +.. _Access Context Manager: https://cloud.google.com/access-context-manager/docs/overview +.. _Client Library Documentation: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-context-manager +.. _Product Documentation: https://cloud.google.com/access-context-manager/docs/overview + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Access Context Manager.`_ +4. `Set up Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Access Context Manager.: https://cloud.google.com/access-context-manager/docs/overview +.. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-context-manager/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7, including 3.14 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-cloud-access-context-manager + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-cloud-access-context-manager + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Access Context Manager + to see other available methods on the client. +- Read the `Access Context Manager Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Access Context Manager Product documentation: https://cloud.google.com/access-context-manager/docs/overview +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + +Environment-Based Examples +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + +Code-Based Examples +^^^^^^^^^^^^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud import library_v1 + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud import library_v1 + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/packages/google-cloud-audit-log/docs/README.rst b/packages/google-cloud-audit-log/docs/README.rst deleted file mode 120000 index 89a0106941ff..000000000000 --- a/packages/google-cloud-audit-log/docs/README.rst +++ /dev/null @@ -1 +0,0 @@ -../README.rst \ No newline at end of file diff --git a/packages/google-cloud-audit-log/docs/README.rst b/packages/google-cloud-audit-log/docs/README.rst new file mode 100644 index 000000000000..0295aa2a2889 --- /dev/null +++ b/packages/google-cloud-audit-log/docs/README.rst @@ -0,0 +1,197 @@ +Python Client for Audit Log API +=============================== + +|preview| |pypi| |versions| + +`Audit Log API`_: + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-audit-log.svg + :target: https://pypi.org/project/google-cloud-audit-log/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-audit-log.svg + :target: https://pypi.org/project/google-cloud-audit-log/ +.. _Audit Log API: https://cloud.google.com/logging/docs/audit +.. _Client Library Documentation: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-audit-log/summary_overview +.. _Product Documentation: https://cloud.google.com/logging/docs/audit + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Audit Log API.`_ +4. `Set up Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Audit Log API.: https://cloud.google.com/logging/docs/audit +.. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-audit-log/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7, including 3.14 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-cloud-audit-log + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-cloud-audit-log + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Audit Log API + to see other available methods on the client. +- Read the `Audit Log API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Audit Log API Product documentation: https://cloud.google.com/logging/docs/audit +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + +Environment-Based Examples +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + +Code-Based Examples +^^^^^^^^^^^^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud import library_v1 + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud import library_v1 + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/packages/grpc-google-iam-v1/docs/README.rst b/packages/grpc-google-iam-v1/docs/README.rst deleted file mode 120000 index 89a0106941ff..000000000000 --- a/packages/grpc-google-iam-v1/docs/README.rst +++ /dev/null @@ -1 +0,0 @@ -../README.rst \ No newline at end of file diff --git a/packages/grpc-google-iam-v1/docs/README.rst b/packages/grpc-google-iam-v1/docs/README.rst new file mode 100644 index 000000000000..b5788d5593e9 --- /dev/null +++ b/packages/grpc-google-iam-v1/docs/README.rst @@ -0,0 +1,197 @@ +Python Client for Cloud Identity and Access Management +====================================================== + +|stable| |pypi| |versions| + +`Cloud Identity and Access Management`_: + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |stable| image:: https://img.shields.io/badge/support-stable-gold.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/grpc-google-iam-v1.svg + :target: https://pypi.org/project/grpc-google-iam-v1/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/grpc-google-iam-v1.svg + :target: https://pypi.org/project/grpc-google-iam-v1/ +.. _Cloud Identity and Access Management: https://cloud.google.com/iam/docs/ +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/grpc-iam/latest +.. _Product Documentation: https://cloud.google.com/iam/docs/ + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Cloud Identity and Access Management.`_ +4. `Set up Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Cloud Identity and Access Management.: https://cloud.google.com/iam/docs/ +.. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/grpc-google-iam-v1/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7, including 3.14 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install grpc-google-iam-v1 + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install grpc-google-iam-v1 + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Cloud Identity and Access Management + to see other available methods on the client. +- Read the `Cloud Identity and Access Management Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Cloud Identity and Access Management Product documentation: https://cloud.google.com/iam/docs/ +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + +Environment-Based Examples +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + +Code-Based Examples +^^^^^^^^^^^^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud import library_v1 + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud import library_v1 + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) From 07990da1b98d2a865c5dbc54d044d1ecddb7998f Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Mon, 10 Nov 2025 20:38:35 +0000 Subject: [PATCH 3/3] restore files for grafeas --- .../grafeas/grafeas/grafeas/gapic_version.py | 16 + .../grafeas/grafeas/grafeas_v1/__init__.py | 228 + .../grafeas/grafeas_v1/gapic_metadata.json | 238 + .../grafeas/grafeas_v1/gapic_version.py | 16 + packages/grafeas/grafeas/grafeas_v1/py.typed | 2 + .../grafeas/grafeas_v1/services/__init__.py | 15 + .../grafeas_v1/services/grafeas/__init__.py | 22 + .../services/grafeas/async_client.py | 1848 +++ .../grafeas_v1/services/grafeas/client.py | 1970 +++ .../grafeas_v1/services/grafeas/pagers.py | 509 + .../services/grafeas/transports/README.rst | 9 + .../services/grafeas/transports/__init__.py | 36 + .../services/grafeas/transports/base.py | 435 + .../services/grafeas/transports/grpc.py | 715 + .../grafeas/transports/grpc_asyncio.py | 895 ++ .../services/grafeas/transports/rest.py | 3034 ++++ .../services/grafeas/transports/rest_base.py | 874 + .../grafeas/grafeas_v1/types/__init__.py | 215 + .../grafeas/grafeas_v1/types/attestation.py | 147 + .../grafeas/grafeas/grafeas_v1/types/build.py | 114 + .../grafeas/grafeas_v1/types/common.py | 380 + .../grafeas/grafeas_v1/types/compliance.py | 214 + .../grafeas/grafeas/grafeas_v1/types/cvss.py | 465 + .../grafeas/grafeas_v1/types/deployment.py | 124 + .../grafeas/grafeas_v1/types/discovery.py | 283 + .../grafeas_v1/types/dsse_attestation.py | 100 + .../grafeas/grafeas_v1/types/grafeas.py | 941 ++ .../grafeas/grafeas/grafeas_v1/types/image.py | 157 + .../grafeas_v1/types/intoto_provenance.py | 246 + .../grafeas_v1/types/intoto_statement.py | 362 + .../grafeas/grafeas_v1/types/package.py | 378 + .../grafeas/grafeas_v1/types/provenance.py | 596 + .../grafeas/grafeas/grafeas_v1/types/sbom.py | 169 + .../grafeas/grafeas_v1/types/secret.py | 154 + .../grafeas/grafeas_v1/types/severity.py | 55 + .../grafeas_v1/types/slsa_provenance.py | 256 + .../types/slsa_provenance_zero_two.py | 240 + .../grafeas/grafeas_v1/types/upgrade.py | 265 + .../grafeas/grafeas/grafeas_v1/types/vex.py | 390 + .../grafeas/grafeas_v1/types/vulnerability.py | 597 + packages/grafeas/mypy.ini | 3 + packages/grafeas/noxfile.py | 616 + ...erated_grafeas_batch_create_notes_async.py | 53 + ...nerated_grafeas_batch_create_notes_sync.py | 53 + ..._grafeas_batch_create_occurrences_async.py | 53 + ...d_grafeas_batch_create_occurrences_sync.py | 53 + ..._v1_generated_grafeas_create_note_async.py | 54 + ...s_v1_generated_grafeas_create_note_sync.py | 54 + ...nerated_grafeas_create_occurrence_async.py | 53 + ...enerated_grafeas_create_occurrence_sync.py | 53 + ..._v1_generated_grafeas_delete_note_async.py | 50 + ...s_v1_generated_grafeas_delete_note_sync.py | 50 + ...nerated_grafeas_delete_occurrence_async.py | 50 + ...enerated_grafeas_delete_occurrence_sync.py | 50 + ...sis_v1_generated_grafeas_get_note_async.py | 53 + ...ysis_v1_generated_grafeas_get_note_sync.py | 53 + ..._generated_grafeas_get_occurrence_async.py | 53 + ...rated_grafeas_get_occurrence_note_async.py | 53 + ...erated_grafeas_get_occurrence_note_sync.py | 53 + ...1_generated_grafeas_get_occurrence_sync.py | 53 + ...ted_grafeas_list_note_occurrences_async.py | 54 + ...ated_grafeas_list_note_occurrences_sync.py | 54 + ...s_v1_generated_grafeas_list_notes_async.py | 54 + ...is_v1_generated_grafeas_list_notes_sync.py | 54 + ...enerated_grafeas_list_occurrences_async.py | 54 + ...generated_grafeas_list_occurrences_sync.py | 54 + ..._v1_generated_grafeas_update_note_async.py | 53 + ...s_v1_generated_grafeas_update_note_sync.py | 53 + ...nerated_grafeas_update_occurrence_async.py | 53 + ...enerated_grafeas_update_occurrence_sync.py | 53 + .../snippet_metadata_grafeas.v1.json | 2353 +++ .../scripts/fixup_grafeas_v1_keywords.py | 189 + packages/grafeas/setup.py | 100 + packages/grafeas/testing/constraints-3.10.txt | 8 + packages/grafeas/testing/constraints-3.11.txt | 8 + packages/grafeas/testing/constraints-3.12.txt | 8 + packages/grafeas/testing/constraints-3.13.txt | 12 + packages/grafeas/testing/constraints-3.14.txt | 12 + packages/grafeas/testing/constraints-3.7.txt | 12 + packages/grafeas/testing/constraints-3.8.txt | 8 + packages/grafeas/testing/constraints-3.9.txt | 8 + packages/grafeas/tests/__init__.py | 15 + packages/grafeas/tests/unit/__init__.py | 15 + packages/grafeas/tests/unit/gapic/__init__.py | 15 + .../tests/unit/gapic/grafeas_v1/__init__.py | 15 + .../unit/gapic/grafeas_v1/test_grafeas.py | 13188 ++++++++++++++++ 86 files changed, 35775 insertions(+) create mode 100644 packages/grafeas/grafeas/grafeas/gapic_version.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/__init__.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json create mode 100644 packages/grafeas/grafeas/grafeas_v1/gapic_version.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/py.typed create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/__init__.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/__init__.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/attestation.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/build.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/common.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/compliance.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/cvss.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/deployment.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/discovery.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/grafeas.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/image.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/package.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/provenance.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/sbom.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/secret.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/severity.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/upgrade.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/vex.py create mode 100644 packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py create mode 100644 packages/grafeas/mypy.ini create mode 100644 packages/grafeas/noxfile.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py create mode 100644 packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py create mode 100644 packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json create mode 100644 packages/grafeas/scripts/fixup_grafeas_v1_keywords.py create mode 100644 packages/grafeas/setup.py create mode 100644 packages/grafeas/testing/constraints-3.10.txt create mode 100644 packages/grafeas/testing/constraints-3.11.txt create mode 100644 packages/grafeas/testing/constraints-3.12.txt create mode 100644 packages/grafeas/testing/constraints-3.13.txt create mode 100644 packages/grafeas/testing/constraints-3.14.txt create mode 100644 packages/grafeas/testing/constraints-3.7.txt create mode 100644 packages/grafeas/testing/constraints-3.8.txt create mode 100644 packages/grafeas/testing/constraints-3.9.txt create mode 100644 packages/grafeas/tests/__init__.py create mode 100644 packages/grafeas/tests/unit/__init__.py create mode 100644 packages/grafeas/tests/unit/gapic/__init__.py create mode 100644 packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py create mode 100644 packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py diff --git a/packages/grafeas/grafeas/grafeas/gapic_version.py b/packages/grafeas/grafeas/grafeas/gapic_version.py new file mode 100644 index 000000000000..f2979c0fa4af --- /dev/null +++ b/packages/grafeas/grafeas/grafeas/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +__version__ = "1.16.0" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/__init__.py b/packages/grafeas/grafeas/grafeas_v1/__init__.py new file mode 100644 index 000000000000..f58b3d96a6bb --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/__init__.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 grafeas.grafeas_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.grafeas import GrafeasAsyncClient, GrafeasClient +from .types.attestation import AttestationNote, AttestationOccurrence, Jwt +from .types.build import BuildNote, BuildOccurrence +from .types.common import ( + BaseImage, + Digest, + Envelope, + EnvelopeSignature, + FileLocation, + LayerDetails, + License, + NoteKind, + RelatedUrl, + Signature, +) +from .types.compliance import ( + ComplianceNote, + ComplianceOccurrence, + ComplianceVersion, + NonCompliantFile, +) +from .types.cvss import CVSS, CVSSv3, CVSSVersion +from .types.deployment import DeploymentNote, DeploymentOccurrence +from .types.discovery import DiscoveryNote, DiscoveryOccurrence +from .types.dsse_attestation import DSSEAttestationNote, DSSEAttestationOccurrence +from .types.grafeas import ( + BatchCreateNotesRequest, + BatchCreateNotesResponse, + BatchCreateOccurrencesRequest, + BatchCreateOccurrencesResponse, + CreateNoteRequest, + CreateOccurrenceRequest, + DeleteNoteRequest, + DeleteOccurrenceRequest, + GetNoteRequest, + GetOccurrenceNoteRequest, + GetOccurrenceRequest, + ListNoteOccurrencesRequest, + ListNoteOccurrencesResponse, + ListNotesRequest, + ListNotesResponse, + ListOccurrencesRequest, + ListOccurrencesResponse, + Note, + Occurrence, + UpdateNoteRequest, + UpdateOccurrenceRequest, +) +from .types.image import Fingerprint, ImageNote, ImageOccurrence, Layer +from .types.intoto_provenance import ( + BuilderConfig, + Completeness, + InTotoProvenance, + Metadata, + Recipe, +) +from .types.intoto_statement import InTotoSlsaProvenanceV1, InTotoStatement, Subject +from .types.package import ( + Architecture, + Distribution, + Location, + PackageNote, + PackageOccurrence, + Version, +) +from .types.provenance import ( + AliasContext, + Artifact, + BuildProvenance, + CloudRepoSourceContext, + Command, + FileHashes, + GerritSourceContext, + GitSourceContext, + Hash, + ProjectRepoId, + RepoId, + Source, + SourceContext, +) +from .types.sbom import ( + SbomReferenceIntotoPayload, + SbomReferenceIntotoPredicate, + SBOMReferenceNote, + SBOMReferenceOccurrence, +) +from .types.secret import ( + SecretKind, + SecretLocation, + SecretNote, + SecretOccurrence, + SecretStatus, +) +from .types.severity import Severity +from .types.slsa_provenance import SlsaProvenance +from .types.slsa_provenance_zero_two import SlsaProvenanceZeroTwo +from .types.upgrade import ( + UpgradeDistribution, + UpgradeNote, + UpgradeOccurrence, + WindowsUpdate, +) +from .types.vex import VulnerabilityAssessmentNote +from .types.vulnerability import VulnerabilityNote, VulnerabilityOccurrence + +__all__ = ( + "GrafeasAsyncClient", + "AliasContext", + "Architecture", + "Artifact", + "AttestationNote", + "AttestationOccurrence", + "BaseImage", + "BatchCreateNotesRequest", + "BatchCreateNotesResponse", + "BatchCreateOccurrencesRequest", + "BatchCreateOccurrencesResponse", + "BuildNote", + "BuildOccurrence", + "BuildProvenance", + "BuilderConfig", + "CVSS", + "CVSSVersion", + "CVSSv3", + "CloudRepoSourceContext", + "Command", + "Completeness", + "ComplianceNote", + "ComplianceOccurrence", + "ComplianceVersion", + "CreateNoteRequest", + "CreateOccurrenceRequest", + "DSSEAttestationNote", + "DSSEAttestationOccurrence", + "DeleteNoteRequest", + "DeleteOccurrenceRequest", + "DeploymentNote", + "DeploymentOccurrence", + "Digest", + "DiscoveryNote", + "DiscoveryOccurrence", + "Distribution", + "Envelope", + "EnvelopeSignature", + "FileHashes", + "FileLocation", + "Fingerprint", + "GerritSourceContext", + "GetNoteRequest", + "GetOccurrenceNoteRequest", + "GetOccurrenceRequest", + "GitSourceContext", + "GrafeasClient", + "Hash", + "ImageNote", + "ImageOccurrence", + "InTotoProvenance", + "InTotoSlsaProvenanceV1", + "InTotoStatement", + "Jwt", + "Layer", + "LayerDetails", + "License", + "ListNoteOccurrencesRequest", + "ListNoteOccurrencesResponse", + "ListNotesRequest", + "ListNotesResponse", + "ListOccurrencesRequest", + "ListOccurrencesResponse", + "Location", + "Metadata", + "NonCompliantFile", + "Note", + "NoteKind", + "Occurrence", + "PackageNote", + "PackageOccurrence", + "ProjectRepoId", + "Recipe", + "RelatedUrl", + "RepoId", + "SBOMReferenceNote", + "SBOMReferenceOccurrence", + "SbomReferenceIntotoPayload", + "SbomReferenceIntotoPredicate", + "SecretKind", + "SecretLocation", + "SecretNote", + "SecretOccurrence", + "SecretStatus", + "Severity", + "Signature", + "SlsaProvenance", + "SlsaProvenanceZeroTwo", + "Source", + "SourceContext", + "Subject", + "UpdateNoteRequest", + "UpdateOccurrenceRequest", + "UpgradeDistribution", + "UpgradeNote", + "UpgradeOccurrence", + "Version", + "VulnerabilityAssessmentNote", + "VulnerabilityNote", + "VulnerabilityOccurrence", + "WindowsUpdate", +) diff --git a/packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json b/packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json new file mode 100644 index 000000000000..ec505dda48a9 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/gapic_metadata.json @@ -0,0 +1,238 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "grafeas.grafeas_v1", + "protoPackage": "grafeas.v1", + "schema": "1.0", + "services": { + "Grafeas": { + "clients": { + "grpc": { + "libraryClient": "GrafeasClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GrafeasAsyncClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + }, + "rest": { + "libraryClient": "GrafeasClient", + "rpcs": { + "BatchCreateNotes": { + "methods": [ + "batch_create_notes" + ] + }, + "BatchCreateOccurrences": { + "methods": [ + "batch_create_occurrences" + ] + }, + "CreateNote": { + "methods": [ + "create_note" + ] + }, + "CreateOccurrence": { + "methods": [ + "create_occurrence" + ] + }, + "DeleteNote": { + "methods": [ + "delete_note" + ] + }, + "DeleteOccurrence": { + "methods": [ + "delete_occurrence" + ] + }, + "GetNote": { + "methods": [ + "get_note" + ] + }, + "GetOccurrence": { + "methods": [ + "get_occurrence" + ] + }, + "GetOccurrenceNote": { + "methods": [ + "get_occurrence_note" + ] + }, + "ListNoteOccurrences": { + "methods": [ + "list_note_occurrences" + ] + }, + "ListNotes": { + "methods": [ + "list_notes" + ] + }, + "ListOccurrences": { + "methods": [ + "list_occurrences" + ] + }, + "UpdateNote": { + "methods": [ + "update_note" + ] + }, + "UpdateOccurrence": { + "methods": [ + "update_occurrence" + ] + } + } + } + } + } + } +} diff --git a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py new file mode 100644 index 000000000000..f2979c0fa4af --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +__version__ = "1.16.0" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/py.typed b/packages/grafeas/grafeas/grafeas_v1/py.typed new file mode 100644 index 000000000000..49e8f71d60b7 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The grafeas package uses inline types. diff --git a/packages/grafeas/grafeas/grafeas_v1/services/__init__.py b/packages/grafeas/grafeas/grafeas_v1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py new file mode 100644 index 000000000000..ce3f2668a5ae --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 .async_client import GrafeasAsyncClient +from .client import GrafeasClient + +__all__ = ( + "GrafeasClient", + "GrafeasAsyncClient", +) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py new file mode 100644 index 000000000000..f88c2f9f5c0f --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/async_client.py @@ -0,0 +1,1848 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from grafeas.grafeas_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.types import ( + attestation, + build, + common, + compliance, + deployment, + discovery, + dsse_attestation, + grafeas, + image, + package, + sbom, + secret, + upgrade, + vex, + vulnerability, +) + +from .client import GrafeasClient +from .transports.base import DEFAULT_CLIENT_INFO, GrafeasTransport +from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class GrafeasAsyncClient: + """`Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + """ + + _client: GrafeasClient + + note_path = staticmethod(GrafeasClient.note_path) + parse_note_path = staticmethod(GrafeasClient.parse_note_path) + occurrence_path = staticmethod(GrafeasClient.occurrence_path) + parse_occurrence_path = staticmethod(GrafeasClient.parse_occurrence_path) + project_path = staticmethod(GrafeasClient.project_path) + parse_project_path = staticmethod(GrafeasClient.parse_project_path) + common_billing_account_path = staticmethod( + GrafeasClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + GrafeasClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(GrafeasClient.common_folder_path) + parse_common_folder_path = staticmethod(GrafeasClient.parse_common_folder_path) + common_organization_path = staticmethod(GrafeasClient.common_organization_path) + parse_common_organization_path = staticmethod( + GrafeasClient.parse_common_organization_path + ) + common_project_path = staticmethod(GrafeasClient.common_project_path) + parse_common_project_path = staticmethod(GrafeasClient.parse_common_project_path) + common_location_path = staticmethod(GrafeasClient.common_location_path) + parse_common_location_path = staticmethod(GrafeasClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GrafeasAsyncClient: The constructed client. + """ + return GrafeasClient.from_service_account_info.__func__(GrafeasAsyncClient, info, *args, **kwargs) # type: ignore + + @property + def transport(self) -> GrafeasTransport: + """Returns the transport used by the client instance. + + Returns: + GrafeasTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = GrafeasClient.get_transport_class + + def __init__( + self, + *, + transport: Union[str, GrafeasTransport] = "grpc_asyncio", + credentials: Optional[ga_credentials.Credentials] = None, + ) -> None: + """Instantiate the grafeas client. + + Args: + transport (Union[str, ~.GrafeasTransport]): The + transport to use. + 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. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = GrafeasClient( + transport=transport, + credentials=credentials, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `grafeas_v1.GrafeasAsyncClient`.", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "grafeas.v1.Grafeas", + "credentialsType": None, + }, + ) + + async def get_occurrence( + self, + request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Gets the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]]): + The request object. Request to get an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceRequest): + request = grafeas.GetOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_occurrence + ] + + # 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_occurrences( + self, + request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListOccurrencesAsyncPager: + r"""Lists occurrences for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]]): + The request object. Request to list occurrences. + parent (:class:`str`): + The name of the project to list occurrences for in the + form of ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager: + Response for listing occurrences. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, filter] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListOccurrencesRequest): + request = grafeas.ListOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_occurrences + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListOccurrencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_occurrence( + self, + request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + await client.delete_occurrence(request=request) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]]): + The request object. Request to delete an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteOccurrenceRequest): + request = grafeas.DeleteOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_occurrence + ] + + # 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 create_occurrence( + self, + request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Creates a new occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]]): + The request object. Request to create a new occurrence. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is + to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): + The occurrence to create. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, occurrence] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateOccurrenceRequest): + request = grafeas.CreateOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrence is not None: + request.occurrence = occurrence + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_occurrence + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_occurrences( + self, + request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Creates new occurrences in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]]): + The request object. Request to create occurrences in + batch. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences + are to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrences (:class:`MutableSequence[grafeas.grafeas_v1.types.Occurrence]`): + The occurrences to create. Max + allowed length is 1000. + + This corresponds to the ``occurrences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, occurrences] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): + request = grafeas.BatchCreateOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrences: + request.occurrences.extend(occurrences) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_create_occurrences + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_occurrence( + self, + request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Updates the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.update_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]]): + The request object. Request to update an occurrence. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (:class:`grafeas.grafeas_v1.types.Occurrence`): + The updated occurrence. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, occurrence, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateOccurrenceRequest): + request = grafeas.UpdateOccurrenceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if occurrence is not None: + request.occurrence = occurrence + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_occurrence + ] + + # 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_occurrence_note( + self, + request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]]): + The request object. Request to get the note to which the + specified occurrence is attached. + name (:class:`str`): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceNoteRequest): + request = grafeas.GetOccurrenceNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_occurrence_note + ] + + # 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_note( + self, + request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]]): + The request object. Request to get a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetNoteRequest): + request = grafeas.GetNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_note] + + # 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_notes( + self, + request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNotesAsyncPager: + r"""Lists notes for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]]): + The request object. Request to list notes. + parent (:class:`str`): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager: + Response for listing notes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, filter] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNotesRequest): + request = grafeas.ListNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_notes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNotesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_note( + self, + request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + await client.delete_note(request=request) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]]): + The request object. Request to delete a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteNoteRequest): + request = grafeas.DeleteNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_note + ] + + # 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 create_note( + self, + request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, + *, + parent: Optional[str] = None, + note_id: Optional[str] = None, + note: Optional[grafeas.Note] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Creates a new note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = await client.create_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]]): + The request object. Request to create a new note. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note_id (:class:`str`): + The ID to use for this note. + This corresponds to the ``note_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (:class:`grafeas.grafeas_v1.types.Note`): + The note to create. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, note_id, note] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateNoteRequest): + request = grafeas.CreateNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if note_id is not None: + request.note_id = note_id + if note is not None: + request.note = note + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_note + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_notes( + self, + request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + notes: Optional[MutableMapping[str, grafeas.Note]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Creates new notes in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_notes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]]): + The request object. Request to create notes in batch. + parent (:class:`str`): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to + be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notes (:class:`MutableMapping[str, grafeas.grafeas_v1.types.Note]`): + The notes to create. Max allowed + length is 1000. + + This corresponds to the ``notes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, notes] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateNotesRequest): + request = grafeas.BatchCreateNotesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + if notes: + request.notes.update(notes) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_create_notes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_note( + self, + request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + note: Optional[grafeas.Note] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Updates the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.update_note(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]]): + The request object. Request to update a note. + name (:class:`str`): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (:class:`grafeas.grafeas_v1.types.Note`): + The updated note. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, note, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateNoteRequest): + request = grafeas.UpdateNoteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if note is not None: + request.note = note + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_note + ] + + # 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_note_occurrences( + self, + request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, + *, + name: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNoteOccurrencesAsyncPager: + r"""Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + async def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]]): + The request object. Request to list occurrences for a + note. + name (:class:`str`): + The name of the note to list occurrences for in the form + of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The filter expression. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager: + Response for listing occurrences for + a note. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, filter] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNoteOccurrencesRequest): + request = grafeas.ListNoteOccurrencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_note_occurrences + ] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNoteOccurrencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "GrafeasAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("GrafeasAsyncClient",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py new file mode 100644 index 000000000000..e286c84b8e18 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/client.py @@ -0,0 +1,1970 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from grafeas.grafeas_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from grafeas.grafeas_v1.services.grafeas import pagers +from grafeas.grafeas_v1.types import ( + attestation, + build, + common, + compliance, + deployment, + discovery, + dsse_attestation, + grafeas, + image, + package, + sbom, + secret, + upgrade, + vex, + vulnerability, +) + +from .transports.base import DEFAULT_CLIENT_INFO, GrafeasTransport +from .transports.grpc import GrafeasGrpcTransport +from .transports.grpc_asyncio import GrafeasGrpcAsyncIOTransport +from .transports.rest import GrafeasRestTransport + + +class GrafeasClientMeta(type): + """Metaclass for the Grafeas client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] + _transport_registry["grpc"] = GrafeasGrpcTransport + _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport + _transport_registry["rest"] = GrafeasRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[GrafeasTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class GrafeasClient(metaclass=GrafeasClientMeta): + """`Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GrafeasClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @property + def transport(self) -> GrafeasTransport: + """Returns the transport used by the client instance. + + Returns: + GrafeasTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def note_path( + project: str, + note: str, + ) -> str: + """Returns a fully-qualified note string.""" + return "projects/{project}/notes/{note}".format( + project=project, + note=note, + ) + + @staticmethod + def parse_note_path(path: str) -> Dict[str, str]: + """Parses a note path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/notes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def occurrence_path( + project: str, + occurrence: str, + ) -> str: + """Returns a fully-qualified occurrence string.""" + return "projects/{project}/occurrences/{occurrence}".format( + project=project, + occurrence=occurrence, + ) + + @staticmethod + def parse_occurrence_path(path: str) -> Dict[str, str]: + """Parses a occurrence path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/occurrences/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_project_path(path: str) -> Dict[str, str]: + """Parses a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + transport: Union[str, GrafeasTransport] = None, + credentials: Optional[ga_credentials.Credentials] = None, + ) -> None: + """Instantiate the grafeas client. + + Args: + transport (Union[str, ~.GrafeasTransport]): The + transport to use. + 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. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + + if isinstance(transport, GrafeasTransport): + self._transport = transport + else: + Transport = GrafeasClient.get_transport_class(transport) + self._transport = Transport(credentials=credentials) + + def get_occurrence( + self, + request: Optional[Union[grafeas.GetOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Gets the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.GetOccurrenceRequest, dict]): + The request object. Request to get an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceRequest): + request = grafeas.GetOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_occurrence] + + # 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_occurrences( + self, + request: Optional[Union[grafeas.ListOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListOccurrencesPager: + r"""Lists occurrences for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.ListOccurrencesRequest, dict]): + The request object. Request to list occurrences. + parent (str): + The name of the project to list occurrences for in the + form of ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager: + Response for listing occurrences. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, filter] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListOccurrencesRequest): + request = grafeas.ListOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_occurrences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListOccurrencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_occurrence( + self, + request: Optional[Union[grafeas.DeleteOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + client.delete_occurrence(request=request) + + Args: + request (Union[grafeas.grafeas_v1.types.DeleteOccurrenceRequest, dict]): + The request object. Request to delete an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteOccurrenceRequest): + request = grafeas.DeleteOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_occurrence] + + # 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 create_occurrence( + self, + request: Optional[Union[grafeas.CreateOccurrenceRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Creates a new occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.CreateOccurrenceRequest, dict]): + The request object. Request to create a new occurrence. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is + to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The occurrence to create. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, occurrence] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateOccurrenceRequest): + request = grafeas.CreateOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrence is not None: + request.occurrence = occurrence + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_occurrence] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_occurrences( + self, + request: Optional[Union[grafeas.BatchCreateOccurrencesRequest, dict]] = None, + *, + parent: Optional[str] = None, + occurrences: Optional[MutableSequence[grafeas.Occurrence]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Creates new occurrences in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest, dict]): + The request object. Request to create occurrences in + batch. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences + are to be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences to create. Max + allowed length is 1000. + + This corresponds to the ``occurrences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, occurrences] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateOccurrencesRequest): + request = grafeas.BatchCreateOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if occurrences is not None: + request.occurrences = occurrences + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_occurrences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_occurrence( + self, + request: Optional[Union[grafeas.UpdateOccurrenceRequest, dict]] = None, + *, + name: Optional[str] = None, + occurrence: Optional[grafeas.Occurrence] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Updates the specified occurrence. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.update_occurrence(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.UpdateOccurrenceRequest, dict]): + The request object. Request to update an occurrence. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The updated occurrence. + This corresponds to the ``occurrence`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, occurrence, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateOccurrenceRequest): + request = grafeas.UpdateOccurrenceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if occurrence is not None: + request.occurrence = occurrence + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_occurrence] + + # 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_occurrence_note( + self, + request: Optional[Union[grafeas.GetOccurrenceNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.GetOccurrenceNoteRequest, dict]): + The request object. Request to get the note to which the + specified occurrence is attached. + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetOccurrenceNoteRequest): + request = grafeas.GetOccurrenceNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_occurrence_note] + + # 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_note( + self, + request: Optional[Union[grafeas.GetNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Gets the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.GetNoteRequest, dict]): + The request object. Request to get a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.GetNoteRequest): + request = grafeas.GetNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_note] + + # 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_notes( + self, + request: Optional[Union[grafeas.ListNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNotesPager: + r"""Lists notes for the specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.ListNotesRequest, dict]): + The request object. Request to list notes. + parent (str): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager: + Response for listing notes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, filter] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNotesRequest): + request = grafeas.ListNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_notes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNotesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_note( + self, + request: Optional[Union[grafeas.DeleteNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + client.delete_note(request=request) + + Args: + request (Union[grafeas.grafeas_v1.types.DeleteNoteRequest, dict]): + The request object. Request to delete a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.DeleteNoteRequest): + request = grafeas.DeleteNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_note] + + # 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 create_note( + self, + request: Optional[Union[grafeas.CreateNoteRequest, dict]] = None, + *, + parent: Optional[str] = None, + note_id: Optional[str] = None, + note: Optional[grafeas.Note] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Creates a new note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = client.create_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.CreateNoteRequest, dict]): + The request object. Request to create a new note. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note_id (str): + The ID to use for this note. + This corresponds to the ``note_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (grafeas.grafeas_v1.types.Note): + The note to create. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, note_id, note] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.CreateNoteRequest): + request = grafeas.CreateNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if note_id is not None: + request.note_id = note_id + if note is not None: + request.note = note + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_note] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_notes( + self, + request: Optional[Union[grafeas.BatchCreateNotesRequest, dict]] = None, + *, + parent: Optional[str] = None, + notes: Optional[MutableMapping[str, grafeas.Note]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Creates new notes in batch. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_notes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.BatchCreateNotesRequest, dict]): + The request object. Request to create notes in batch. + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to + be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): + The notes to create. Max allowed + length is 1000. + + This corresponds to the ``notes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, notes] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.BatchCreateNotesRequest): + request = grafeas.BatchCreateNotesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notes is not None: + request.notes = notes + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_notes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_note( + self, + request: Optional[Union[grafeas.UpdateNoteRequest, dict]] = None, + *, + name: Optional[str] = None, + note: Optional[grafeas.Note] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Updates the specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = client.update_note(request=request) + + # Handle the response + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.UpdateNoteRequest, dict]): + The request object. Request to update a note. + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + note (grafeas.grafeas_v1.types.Note): + The updated note. + This corresponds to the ``note`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.types.Note: + A type of analysis that can be done + for a resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, note, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.UpdateNoteRequest): + request = grafeas.UpdateNoteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if note is not None: + request.note = note + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_note] + + # 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_note_occurrences( + self, + request: Optional[Union[grafeas.ListNoteOccurrencesRequest, dict]] = None, + *, + name: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListNoteOccurrencesPager: + r"""Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from grafeas import grafeas_v1 + + def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[grafeas.grafeas_v1.types.ListNoteOccurrencesRequest, dict]): + The request object. Request to list occurrences for a + note. + name (str): + The name of the note to list occurrences for in the form + of ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The filter expression. + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager: + Response for listing occurrences for + a note. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, filter] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, grafeas.ListNoteOccurrencesRequest): + request = grafeas.ListNoteOccurrencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_note_occurrences] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNoteOccurrencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "GrafeasClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("GrafeasClient",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py new file mode 100644 index 000000000000..c062b968fcda --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/pagers.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from grafeas.grafeas_v1.types import grafeas + + +class ListOccurrencesPager: + """A pager for iterating through ``list_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., grafeas.ListOccurrencesResponse], + request: grafeas.ListOccurrencesRequest, + response: grafeas.ListOccurrencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListOccurrencesResponse): + The initial response object. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = grafeas.ListOccurrencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[grafeas.ListOccurrencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[grafeas.Occurrence]: + for page in self.pages: + yield from page.occurrences + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListOccurrencesAsyncPager: + """A pager for iterating through ``list_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListOccurrencesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[grafeas.ListOccurrencesResponse]], + request: grafeas.ListOccurrencesRequest, + response: grafeas.ListOccurrencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListOccurrencesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = grafeas.ListOccurrencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[grafeas.ListOccurrencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[grafeas.Occurrence]: + async def async_generator(): + async for page in self.pages: + for response in page.occurrences: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotesPager: + """A pager for iterating through ``list_notes`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotes`` requests and continue to iterate + through the ``notes`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., grafeas.ListNotesResponse], + request: grafeas.ListNotesRequest, + response: grafeas.ListNotesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNotesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNotesResponse): + The initial response object. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = grafeas.ListNotesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[grafeas.ListNotesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[grafeas.Note]: + for page in self.pages: + yield from page.notes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotesAsyncPager: + """A pager for iterating through ``list_notes`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNotesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotes`` requests and continue to iterate + through the ``notes`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNotesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[grafeas.ListNotesResponse]], + request: grafeas.ListNotesRequest, + response: grafeas.ListNotesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNotesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNotesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = grafeas.ListNotesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[grafeas.ListNotesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[grafeas.Note]: + async def async_generator(): + async for page in self.pages: + for response in page.notes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNoteOccurrencesPager: + """A pager for iterating through ``list_note_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNoteOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., grafeas.ListNoteOccurrencesResponse], + request: grafeas.ListNoteOccurrencesRequest, + response: grafeas.ListNoteOccurrencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): + The initial response object. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = grafeas.ListNoteOccurrencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[grafeas.ListNoteOccurrencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[grafeas.Occurrence]: + for page in self.pages: + yield from page.occurrences + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNoteOccurrencesAsyncPager: + """A pager for iterating through ``list_note_occurrences`` requests. + + This class thinly wraps an initial + :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``occurrences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNoteOccurrences`` requests and continue to iterate + through the ``occurrences`` field on the + corresponding responses. + + All the usual :class:`grafeas.grafeas_v1.types.ListNoteOccurrencesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[grafeas.ListNoteOccurrencesResponse]], + request: grafeas.ListNoteOccurrencesRequest, + response: grafeas.ListNoteOccurrencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (grafeas.grafeas_v1.types.ListNoteOccurrencesRequest): + The initial request object. + response (grafeas.grafeas_v1.types.ListNoteOccurrencesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = grafeas.ListNoteOccurrencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[grafeas.ListNoteOccurrencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[grafeas.Occurrence]: + async def async_generator(): + async for page in self.pages: + for response in page.occurrences: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst new file mode 100644 index 000000000000..1085202fe2c8 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GrafeasTransport` is the ABC for all transports. +- public child `GrafeasGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GrafeasGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGrafeasRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GrafeasRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py new file mode 100644 index 000000000000..61a079d41d8b --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import GrafeasTransport +from .grpc import GrafeasGrpcTransport +from .grpc_asyncio import GrafeasGrpcAsyncIOTransport +from .rest import GrafeasRestInterceptor, GrafeasRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] +_transport_registry["grpc"] = GrafeasGrpcTransport +_transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport +_transport_registry["rest"] = GrafeasRestTransport + +__all__ = ( + "GrafeasTransport", + "GrafeasGrpcTransport", + "GrafeasGrpcAsyncIOTransport", + "GrafeasRestTransport", + "GrafeasRestInterceptor", +) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py new file mode 100644 index 000000000000..f02e4dbde1cc --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/base.py @@ -0,0 +1,435 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +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.oauth2 import service_account # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from grafeas.grafeas_v1 import gapic_version as package_version +from grafeas.grafeas_v1.types import grafeas + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class GrafeasTransport(abc.ABC): + """Abstract transport class for Grafeas.""" + + AUTH_SCOPES = () + + DEFAULT_HOST: str = "" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: ''). + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_occurrence: gapic_v1.method.wrap_method( + self.get_occurrence, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_occurrences: gapic_v1.method.wrap_method( + self.list_occurrences, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_occurrence: gapic_v1.method.wrap_method( + self.delete_occurrence, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_occurrence: gapic_v1.method.wrap_method( + self.create_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_occurrences: gapic_v1.method.wrap_method( + self.batch_create_occurrences, + default_timeout=30.0, + client_info=client_info, + ), + self.update_occurrence: gapic_v1.method.wrap_method( + self.update_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.get_occurrence_note: gapic_v1.method.wrap_method( + self.get_occurrence_note, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_note: gapic_v1.method.wrap_method( + self.get_note, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_notes: gapic_v1.method.wrap_method( + self.list_notes, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_note: gapic_v1.method.wrap_method( + self.delete_note, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_note: gapic_v1.method.wrap_method( + self.create_note, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_notes: gapic_v1.method.wrap_method( + self.batch_create_notes, + default_timeout=30.0, + client_info=client_info, + ), + self.update_note: gapic_v1.method.wrap_method( + self.update_note, + default_timeout=30.0, + client_info=client_info, + ), + self.list_note_occurrences: gapic_v1.method.wrap_method( + self.list_note_occurrences, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_occurrence( + self, + ) -> Callable[ + [grafeas.GetOccurrenceRequest], + Union[grafeas.Occurrence, Awaitable[grafeas.Occurrence]], + ]: + raise NotImplementedError() + + @property + def list_occurrences( + self, + ) -> Callable[ + [grafeas.ListOccurrencesRequest], + Union[ + grafeas.ListOccurrencesResponse, Awaitable[grafeas.ListOccurrencesResponse] + ], + ]: + raise NotImplementedError() + + @property + def delete_occurrence( + self, + ) -> Callable[ + [grafeas.DeleteOccurrenceRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_occurrence( + self, + ) -> Callable[ + [grafeas.CreateOccurrenceRequest], + Union[grafeas.Occurrence, Awaitable[grafeas.Occurrence]], + ]: + raise NotImplementedError() + + @property + def batch_create_occurrences( + self, + ) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + Union[ + grafeas.BatchCreateOccurrencesResponse, + Awaitable[grafeas.BatchCreateOccurrencesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_occurrence( + self, + ) -> Callable[ + [grafeas.UpdateOccurrenceRequest], + Union[grafeas.Occurrence, Awaitable[grafeas.Occurrence]], + ]: + raise NotImplementedError() + + @property + def get_occurrence_note( + self, + ) -> Callable[ + [grafeas.GetOccurrenceNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] + ]: + raise NotImplementedError() + + @property + def get_note( + self, + ) -> Callable[ + [grafeas.GetNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] + ]: + raise NotImplementedError() + + @property + def list_notes( + self, + ) -> Callable[ + [grafeas.ListNotesRequest], + Union[grafeas.ListNotesResponse, Awaitable[grafeas.ListNotesResponse]], + ]: + raise NotImplementedError() + + @property + def delete_note( + self, + ) -> Callable[ + [grafeas.DeleteNoteRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def create_note( + self, + ) -> Callable[ + [grafeas.CreateNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] + ]: + raise NotImplementedError() + + @property + def batch_create_notes( + self, + ) -> Callable[ + [grafeas.BatchCreateNotesRequest], + Union[ + grafeas.BatchCreateNotesResponse, + Awaitable[grafeas.BatchCreateNotesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_note( + self, + ) -> Callable[ + [grafeas.UpdateNoteRequest], Union[grafeas.Note, Awaitable[grafeas.Note]] + ]: + raise NotImplementedError() + + @property + def list_note_occurrences( + self, + ) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + Union[ + grafeas.ListNoteOccurrencesResponse, + Awaitable[grafeas.ListNoteOccurrencesResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("GrafeasTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py new file mode 100644 index 000000000000..0424704ce4bf --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc.py @@ -0,0 +1,715 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +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.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import grafeas + +from .base import DEFAULT_CLIENT_INFO, GrafeasTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GrafeasGrpcTransport(GrafeasTransport): + """gRPC backend transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: ''). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def get_occurrence( + self, + ) -> Callable[[grafeas.GetOccurrenceRequest], grafeas.Occurrence]: + r"""Return a callable for the get occurrence method over gRPC. + + Gets the specified occurrence. + + Returns: + Callable[[~.GetOccurrenceRequest], + ~.Occurrence]: + 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_occurrence" not in self._stubs: + self._stubs["get_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/GetOccurrence", + request_serializer=grafeas.GetOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs["get_occurrence"] + + @property + def list_occurrences( + self, + ) -> Callable[[grafeas.ListOccurrencesRequest], grafeas.ListOccurrencesResponse]: + r"""Return a callable for the list occurrences method over gRPC. + + Lists occurrences for the specified project. + + Returns: + Callable[[~.ListOccurrencesRequest], + ~.ListOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_occurrences" not in self._stubs: + self._stubs["list_occurrences"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/ListOccurrences", + request_serializer=grafeas.ListOccurrencesRequest.serialize, + response_deserializer=grafeas.ListOccurrencesResponse.deserialize, + ) + return self._stubs["list_occurrences"] + + @property + def delete_occurrence( + self, + ) -> Callable[[grafeas.DeleteOccurrenceRequest], empty_pb2.Empty]: + r"""Return a callable for the delete occurrence method over gRPC. + + Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Returns: + Callable[[~.DeleteOccurrenceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_occurrence" not in self._stubs: + self._stubs["delete_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/DeleteOccurrence", + request_serializer=grafeas.DeleteOccurrenceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_occurrence"] + + @property + def create_occurrence( + self, + ) -> Callable[[grafeas.CreateOccurrenceRequest], grafeas.Occurrence]: + r"""Return a callable for the create occurrence method over gRPC. + + Creates a new occurrence. + + Returns: + Callable[[~.CreateOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_occurrence" not in self._stubs: + self._stubs["create_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/CreateOccurrence", + request_serializer=grafeas.CreateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs["create_occurrence"] + + @property + def batch_create_occurrences( + self, + ) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], grafeas.BatchCreateOccurrencesResponse + ]: + r"""Return a callable for the batch create occurrences method over gRPC. + + Creates new occurrences in batch. + + Returns: + Callable[[~.BatchCreateOccurrencesRequest], + ~.BatchCreateOccurrencesResponse]: + 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 "batch_create_occurrences" not in self._stubs: + self._stubs["batch_create_occurrences"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/BatchCreateOccurrences", + request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, + response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, + ) + return self._stubs["batch_create_occurrences"] + + @property + def update_occurrence( + self, + ) -> Callable[[grafeas.UpdateOccurrenceRequest], grafeas.Occurrence]: + r"""Return a callable for the update occurrence method over gRPC. + + Updates the specified occurrence. + + Returns: + Callable[[~.UpdateOccurrenceRequest], + ~.Occurrence]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_occurrence" not in self._stubs: + self._stubs["update_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/UpdateOccurrence", + request_serializer=grafeas.UpdateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs["update_occurrence"] + + @property + def get_occurrence_note( + self, + ) -> Callable[[grafeas.GetOccurrenceNoteRequest], grafeas.Note]: + r"""Return a callable for the get occurrence note method over gRPC. + + Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Returns: + Callable[[~.GetOccurrenceNoteRequest], + ~.Note]: + 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_occurrence_note" not in self._stubs: + self._stubs["get_occurrence_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/GetOccurrenceNote", + request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["get_occurrence_note"] + + @property + def get_note(self) -> Callable[[grafeas.GetNoteRequest], grafeas.Note]: + r"""Return a callable for the get note method over gRPC. + + Gets the specified note. + + Returns: + Callable[[~.GetNoteRequest], + ~.Note]: + 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_note" not in self._stubs: + self._stubs["get_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/GetNote", + request_serializer=grafeas.GetNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["get_note"] + + @property + def list_notes( + self, + ) -> Callable[[grafeas.ListNotesRequest], grafeas.ListNotesResponse]: + r"""Return a callable for the list notes method over gRPC. + + Lists notes for the specified project. + + Returns: + Callable[[~.ListNotesRequest], + ~.ListNotesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_notes" not in self._stubs: + self._stubs["list_notes"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/ListNotes", + request_serializer=grafeas.ListNotesRequest.serialize, + response_deserializer=grafeas.ListNotesResponse.deserialize, + ) + return self._stubs["list_notes"] + + @property + def delete_note(self) -> Callable[[grafeas.DeleteNoteRequest], empty_pb2.Empty]: + r"""Return a callable for the delete note method over gRPC. + + Deletes the specified note. + + Returns: + Callable[[~.DeleteNoteRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_note" not in self._stubs: + self._stubs["delete_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/DeleteNote", + request_serializer=grafeas.DeleteNoteRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_note"] + + @property + def create_note(self) -> Callable[[grafeas.CreateNoteRequest], grafeas.Note]: + r"""Return a callable for the create note method over gRPC. + + Creates a new note. + + Returns: + Callable[[~.CreateNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_note" not in self._stubs: + self._stubs["create_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/CreateNote", + request_serializer=grafeas.CreateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["create_note"] + + @property + def batch_create_notes( + self, + ) -> Callable[[grafeas.BatchCreateNotesRequest], grafeas.BatchCreateNotesResponse]: + r"""Return a callable for the batch create notes method over gRPC. + + Creates new notes in batch. + + Returns: + Callable[[~.BatchCreateNotesRequest], + ~.BatchCreateNotesResponse]: + 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 "batch_create_notes" not in self._stubs: + self._stubs["batch_create_notes"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/BatchCreateNotes", + request_serializer=grafeas.BatchCreateNotesRequest.serialize, + response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, + ) + return self._stubs["batch_create_notes"] + + @property + def update_note(self) -> Callable[[grafeas.UpdateNoteRequest], grafeas.Note]: + r"""Return a callable for the update note method over gRPC. + + Updates the specified note. + + Returns: + Callable[[~.UpdateNoteRequest], + ~.Note]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_note" not in self._stubs: + self._stubs["update_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/UpdateNote", + request_serializer=grafeas.UpdateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["update_note"] + + @property + def list_note_occurrences( + self, + ) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], grafeas.ListNoteOccurrencesResponse + ]: + r"""Return a callable for the list note occurrences method over gRPC. + + Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Returns: + Callable[[~.ListNoteOccurrencesRequest], + ~.ListNoteOccurrencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_note_occurrences" not in self._stubs: + self._stubs["list_note_occurrences"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/ListNoteOccurrences", + request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, + response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, + ) + return self._stubs["list_note_occurrences"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("GrafeasGrpcTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py new file mode 100644 index 000000000000..63844b89b159 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/grpc_asyncio.py @@ -0,0 +1,895 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import grafeas + +from .base import DEFAULT_CLIENT_INFO, GrafeasTransport +from .grpc import GrafeasGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GrafeasGrpcAsyncIOTransport(GrafeasTransport): + """gRPC AsyncIO backend transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: ''). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_occurrence( + self, + ) -> Callable[[grafeas.GetOccurrenceRequest], Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the get occurrence method over gRPC. + + Gets the specified occurrence. + + Returns: + Callable[[~.GetOccurrenceRequest], + Awaitable[~.Occurrence]]: + 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_occurrence" not in self._stubs: + self._stubs["get_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/GetOccurrence", + request_serializer=grafeas.GetOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs["get_occurrence"] + + @property + def list_occurrences( + self, + ) -> Callable[ + [grafeas.ListOccurrencesRequest], Awaitable[grafeas.ListOccurrencesResponse] + ]: + r"""Return a callable for the list occurrences method over gRPC. + + Lists occurrences for the specified project. + + Returns: + Callable[[~.ListOccurrencesRequest], + Awaitable[~.ListOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_occurrences" not in self._stubs: + self._stubs["list_occurrences"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/ListOccurrences", + request_serializer=grafeas.ListOccurrencesRequest.serialize, + response_deserializer=grafeas.ListOccurrencesResponse.deserialize, + ) + return self._stubs["list_occurrences"] + + @property + def delete_occurrence( + self, + ) -> Callable[[grafeas.DeleteOccurrenceRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete occurrence method over gRPC. + + Deletes the specified occurrence. For example, use + this method to delete an occurrence when the occurrence + is no longer applicable for the given resource. + + Returns: + Callable[[~.DeleteOccurrenceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_occurrence" not in self._stubs: + self._stubs["delete_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/DeleteOccurrence", + request_serializer=grafeas.DeleteOccurrenceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_occurrence"] + + @property + def create_occurrence( + self, + ) -> Callable[[grafeas.CreateOccurrenceRequest], Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the create occurrence method over gRPC. + + Creates a new occurrence. + + Returns: + Callable[[~.CreateOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_occurrence" not in self._stubs: + self._stubs["create_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/CreateOccurrence", + request_serializer=grafeas.CreateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs["create_occurrence"] + + @property + def batch_create_occurrences( + self, + ) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], + Awaitable[grafeas.BatchCreateOccurrencesResponse], + ]: + r"""Return a callable for the batch create occurrences method over gRPC. + + Creates new occurrences in batch. + + Returns: + Callable[[~.BatchCreateOccurrencesRequest], + Awaitable[~.BatchCreateOccurrencesResponse]]: + 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 "batch_create_occurrences" not in self._stubs: + self._stubs["batch_create_occurrences"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/BatchCreateOccurrences", + request_serializer=grafeas.BatchCreateOccurrencesRequest.serialize, + response_deserializer=grafeas.BatchCreateOccurrencesResponse.deserialize, + ) + return self._stubs["batch_create_occurrences"] + + @property + def update_occurrence( + self, + ) -> Callable[[grafeas.UpdateOccurrenceRequest], Awaitable[grafeas.Occurrence]]: + r"""Return a callable for the update occurrence method over gRPC. + + Updates the specified occurrence. + + Returns: + Callable[[~.UpdateOccurrenceRequest], + Awaitable[~.Occurrence]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_occurrence" not in self._stubs: + self._stubs["update_occurrence"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/UpdateOccurrence", + request_serializer=grafeas.UpdateOccurrenceRequest.serialize, + response_deserializer=grafeas.Occurrence.deserialize, + ) + return self._stubs["update_occurrence"] + + @property + def get_occurrence_note( + self, + ) -> Callable[[grafeas.GetOccurrenceNoteRequest], Awaitable[grafeas.Note]]: + r"""Return a callable for the get occurrence note method over gRPC. + + Gets the note attached to the specified occurrence. + Consumer projects can use this method to get a note that + belongs to a provider project. + + Returns: + Callable[[~.GetOccurrenceNoteRequest], + Awaitable[~.Note]]: + 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_occurrence_note" not in self._stubs: + self._stubs["get_occurrence_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/GetOccurrenceNote", + request_serializer=grafeas.GetOccurrenceNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["get_occurrence_note"] + + @property + def get_note(self) -> Callable[[grafeas.GetNoteRequest], Awaitable[grafeas.Note]]: + r"""Return a callable for the get note method over gRPC. + + Gets the specified note. + + Returns: + Callable[[~.GetNoteRequest], + Awaitable[~.Note]]: + 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_note" not in self._stubs: + self._stubs["get_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/GetNote", + request_serializer=grafeas.GetNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["get_note"] + + @property + def list_notes( + self, + ) -> Callable[[grafeas.ListNotesRequest], Awaitable[grafeas.ListNotesResponse]]: + r"""Return a callable for the list notes method over gRPC. + + Lists notes for the specified project. + + Returns: + Callable[[~.ListNotesRequest], + Awaitable[~.ListNotesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_notes" not in self._stubs: + self._stubs["list_notes"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/ListNotes", + request_serializer=grafeas.ListNotesRequest.serialize, + response_deserializer=grafeas.ListNotesResponse.deserialize, + ) + return self._stubs["list_notes"] + + @property + def delete_note( + self, + ) -> Callable[[grafeas.DeleteNoteRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete note method over gRPC. + + Deletes the specified note. + + Returns: + Callable[[~.DeleteNoteRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_note" not in self._stubs: + self._stubs["delete_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/DeleteNote", + request_serializer=grafeas.DeleteNoteRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_note"] + + @property + def create_note( + self, + ) -> Callable[[grafeas.CreateNoteRequest], Awaitable[grafeas.Note]]: + r"""Return a callable for the create note method over gRPC. + + Creates a new note. + + Returns: + Callable[[~.CreateNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_note" not in self._stubs: + self._stubs["create_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/CreateNote", + request_serializer=grafeas.CreateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["create_note"] + + @property + def batch_create_notes( + self, + ) -> Callable[ + [grafeas.BatchCreateNotesRequest], Awaitable[grafeas.BatchCreateNotesResponse] + ]: + r"""Return a callable for the batch create notes method over gRPC. + + Creates new notes in batch. + + Returns: + Callable[[~.BatchCreateNotesRequest], + Awaitable[~.BatchCreateNotesResponse]]: + 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 "batch_create_notes" not in self._stubs: + self._stubs["batch_create_notes"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/BatchCreateNotes", + request_serializer=grafeas.BatchCreateNotesRequest.serialize, + response_deserializer=grafeas.BatchCreateNotesResponse.deserialize, + ) + return self._stubs["batch_create_notes"] + + @property + def update_note( + self, + ) -> Callable[[grafeas.UpdateNoteRequest], Awaitable[grafeas.Note]]: + r"""Return a callable for the update note method over gRPC. + + Updates the specified note. + + Returns: + Callable[[~.UpdateNoteRequest], + Awaitable[~.Note]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_note" not in self._stubs: + self._stubs["update_note"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/UpdateNote", + request_serializer=grafeas.UpdateNoteRequest.serialize, + response_deserializer=grafeas.Note.deserialize, + ) + return self._stubs["update_note"] + + @property + def list_note_occurrences( + self, + ) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], + Awaitable[grafeas.ListNoteOccurrencesResponse], + ]: + r"""Return a callable for the list note occurrences method over gRPC. + + Lists occurrences referencing the specified note. + Provider projects can use this method to get all + occurrences across consumer projects referencing the + specified note. + + Returns: + Callable[[~.ListNoteOccurrencesRequest], + Awaitable[~.ListNoteOccurrencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_note_occurrences" not in self._stubs: + self._stubs["list_note_occurrences"] = self._logged_channel.unary_unary( + "/grafeas.v1.Grafeas/ListNoteOccurrences", + request_serializer=grafeas.ListNoteOccurrencesRequest.serialize, + response_deserializer=grafeas.ListNoteOccurrencesResponse.deserialize, + ) + return self._stubs["list_note_occurrences"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_occurrence: self._wrap_method( + self.get_occurrence, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_occurrences: self._wrap_method( + self.list_occurrences, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_occurrence: self._wrap_method( + self.delete_occurrence, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_occurrence: self._wrap_method( + self.create_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_occurrences: self._wrap_method( + self.batch_create_occurrences, + default_timeout=30.0, + client_info=client_info, + ), + self.update_occurrence: self._wrap_method( + self.update_occurrence, + default_timeout=30.0, + client_info=client_info, + ), + self.get_occurrence_note: self._wrap_method( + self.get_occurrence_note, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_note: self._wrap_method( + self.get_note, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_notes: self._wrap_method( + self.list_notes, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_note: self._wrap_method( + self.delete_note, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_note: self._wrap_method( + self.create_note, + default_timeout=30.0, + client_info=client_info, + ), + self.batch_create_notes: self._wrap_method( + self.batch_create_notes, + default_timeout=30.0, + client_info=client_info, + ), + self.update_note: self._wrap_method( + self.update_note, + default_timeout=30.0, + client_info=client_info, + ), + self.list_note_occurrences: self._wrap_method( + self.list_note_occurrences, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("GrafeasGrpcAsyncIOTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py new file mode 100644 index 000000000000..cadb84765d85 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest.py @@ -0,0 +1,3034 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from grafeas.grafeas_v1.types import grafeas + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseGrafeasRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class GrafeasRestInterceptor: + """Interceptor for Grafeas. + + 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 GrafeasRestTransport. + + .. code-block:: python + class MyCustomGrafeasInterceptor(GrafeasRestInterceptor): + def pre_batch_create_notes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_notes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_create_occurrences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_occurrences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_occurrence_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_occurrence_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_note_occurrences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_note_occurrences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_occurrences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_occurrences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_note(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_note(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GrafeasRestTransport(interceptor=MyCustomGrafeasInterceptor()) + client = GrafeasClient(transport=transport) + + + """ + + def pre_batch_create_notes( + self, + request: grafeas.BatchCreateNotesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.BatchCreateNotesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for batch_create_notes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_batch_create_notes( + self, response: grafeas.BatchCreateNotesResponse + ) -> grafeas.BatchCreateNotesResponse: + """Post-rpc interceptor for batch_create_notes + + DEPRECATED. Please use the `post_batch_create_notes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_batch_create_notes` interceptor runs + before the `post_batch_create_notes_with_metadata` interceptor. + """ + return response + + def post_batch_create_notes_with_metadata( + self, + response: grafeas.BatchCreateNotesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.BatchCreateNotesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for batch_create_notes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_batch_create_notes_with_metadata` + interceptor in new development instead of the `post_batch_create_notes` interceptor. + When both interceptors are used, this `post_batch_create_notes_with_metadata` interceptor runs after the + `post_batch_create_notes` interceptor. The (possibly modified) response returned by + `post_batch_create_notes` will be passed to + `post_batch_create_notes_with_metadata`. + """ + return response, metadata + + def pre_batch_create_occurrences( + self, + request: grafeas.BatchCreateOccurrencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.BatchCreateOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for batch_create_occurrences + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_batch_create_occurrences( + self, response: grafeas.BatchCreateOccurrencesResponse + ) -> grafeas.BatchCreateOccurrencesResponse: + """Post-rpc interceptor for batch_create_occurrences + + DEPRECATED. Please use the `post_batch_create_occurrences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_batch_create_occurrences` interceptor runs + before the `post_batch_create_occurrences_with_metadata` interceptor. + """ + return response + + def post_batch_create_occurrences_with_metadata( + self, + response: grafeas.BatchCreateOccurrencesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.BatchCreateOccurrencesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for batch_create_occurrences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_batch_create_occurrences_with_metadata` + interceptor in new development instead of the `post_batch_create_occurrences` interceptor. + When both interceptors are used, this `post_batch_create_occurrences_with_metadata` interceptor runs after the + `post_batch_create_occurrences` interceptor. The (possibly modified) response returned by + `post_batch_create_occurrences` will be passed to + `post_batch_create_occurrences_with_metadata`. + """ + return response, metadata + + def pre_create_note( + self, + request: grafeas.CreateNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.CreateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_create_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for create_note + + DEPRECATED. Please use the `post_create_note_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_create_note` interceptor runs + before the `post_create_note_with_metadata` interceptor. + """ + return response + + def post_create_note_with_metadata( + self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_note + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_create_note_with_metadata` + interceptor in new development instead of the `post_create_note` interceptor. + When both interceptors are used, this `post_create_note_with_metadata` interceptor runs after the + `post_create_note` interceptor. The (possibly modified) response returned by + `post_create_note` will be passed to + `post_create_note_with_metadata`. + """ + return response, metadata + + def pre_create_occurrence( + self, + request: grafeas.CreateOccurrenceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.CreateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_create_occurrence( + self, response: grafeas.Occurrence + ) -> grafeas.Occurrence: + """Post-rpc interceptor for create_occurrence + + DEPRECATED. Please use the `post_create_occurrence_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_create_occurrence` interceptor runs + before the `post_create_occurrence_with_metadata` interceptor. + """ + return response + + def post_create_occurrence_with_metadata( + self, + response: grafeas.Occurrence, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.Occurrence, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_occurrence + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_create_occurrence_with_metadata` + interceptor in new development instead of the `post_create_occurrence` interceptor. + When both interceptors are used, this `post_create_occurrence_with_metadata` interceptor runs after the + `post_create_occurrence` interceptor. The (possibly modified) response returned by + `post_create_occurrence` will be passed to + `post_create_occurrence_with_metadata`. + """ + return response, metadata + + def pre_delete_note( + self, + request: grafeas.DeleteNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.DeleteNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def pre_delete_occurrence( + self, + request: grafeas.DeleteOccurrenceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.DeleteOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def pre_get_note( + self, + request: grafeas.GetNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.GetNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_get_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for get_note + + DEPRECATED. Please use the `post_get_note_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_get_note` interceptor runs + before the `post_get_note_with_metadata` interceptor. + """ + return response + + def post_get_note_with_metadata( + self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_note + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_get_note_with_metadata` + interceptor in new development instead of the `post_get_note` interceptor. + When both interceptors are used, this `post_get_note_with_metadata` interceptor runs after the + `post_get_note` interceptor. The (possibly modified) response returned by + `post_get_note` will be passed to + `post_get_note_with_metadata`. + """ + return response, metadata + + def pre_get_occurrence( + self, + request: grafeas.GetOccurrenceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.GetOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_get_occurrence(self, response: grafeas.Occurrence) -> grafeas.Occurrence: + """Post-rpc interceptor for get_occurrence + + DEPRECATED. Please use the `post_get_occurrence_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_get_occurrence` interceptor runs + before the `post_get_occurrence_with_metadata` interceptor. + """ + return response + + def post_get_occurrence_with_metadata( + self, + response: grafeas.Occurrence, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.Occurrence, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_occurrence + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_get_occurrence_with_metadata` + interceptor in new development instead of the `post_get_occurrence` interceptor. + When both interceptors are used, this `post_get_occurrence_with_metadata` interceptor runs after the + `post_get_occurrence` interceptor. The (possibly modified) response returned by + `post_get_occurrence` will be passed to + `post_get_occurrence_with_metadata`. + """ + return response, metadata + + def pre_get_occurrence_note( + self, + request: grafeas.GetOccurrenceNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.GetOccurrenceNoteRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_occurrence_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_get_occurrence_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for get_occurrence_note + + DEPRECATED. Please use the `post_get_occurrence_note_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_get_occurrence_note` interceptor runs + before the `post_get_occurrence_note_with_metadata` interceptor. + """ + return response + + def post_get_occurrence_note_with_metadata( + self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_occurrence_note + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_get_occurrence_note_with_metadata` + interceptor in new development instead of the `post_get_occurrence_note` interceptor. + When both interceptors are used, this `post_get_occurrence_note_with_metadata` interceptor runs after the + `post_get_occurrence_note` interceptor. The (possibly modified) response returned by + `post_get_occurrence_note` will be passed to + `post_get_occurrence_note_with_metadata`. + """ + return response, metadata + + def pre_list_note_occurrences( + self, + request: grafeas.ListNoteOccurrencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.ListNoteOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_note_occurrences + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_list_note_occurrences( + self, response: grafeas.ListNoteOccurrencesResponse + ) -> grafeas.ListNoteOccurrencesResponse: + """Post-rpc interceptor for list_note_occurrences + + DEPRECATED. Please use the `post_list_note_occurrences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_list_note_occurrences` interceptor runs + before the `post_list_note_occurrences_with_metadata` interceptor. + """ + return response + + def post_list_note_occurrences_with_metadata( + self, + response: grafeas.ListNoteOccurrencesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.ListNoteOccurrencesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_note_occurrences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_list_note_occurrences_with_metadata` + interceptor in new development instead of the `post_list_note_occurrences` interceptor. + When both interceptors are used, this `post_list_note_occurrences_with_metadata` interceptor runs after the + `post_list_note_occurrences` interceptor. The (possibly modified) response returned by + `post_list_note_occurrences` will be passed to + `post_list_note_occurrences_with_metadata`. + """ + return response, metadata + + def pre_list_notes( + self, + request: grafeas.ListNotesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.ListNotesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_notes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_list_notes( + self, response: grafeas.ListNotesResponse + ) -> grafeas.ListNotesResponse: + """Post-rpc interceptor for list_notes + + DEPRECATED. Please use the `post_list_notes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_list_notes` interceptor runs + before the `post_list_notes_with_metadata` interceptor. + """ + return response + + def post_list_notes_with_metadata( + self, + response: grafeas.ListNotesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.ListNotesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_notes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_list_notes_with_metadata` + interceptor in new development instead of the `post_list_notes` interceptor. + When both interceptors are used, this `post_list_notes_with_metadata` interceptor runs after the + `post_list_notes` interceptor. The (possibly modified) response returned by + `post_list_notes` will be passed to + `post_list_notes_with_metadata`. + """ + return response, metadata + + def pre_list_occurrences( + self, + request: grafeas.ListOccurrencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.ListOccurrencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_occurrences + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_list_occurrences( + self, response: grafeas.ListOccurrencesResponse + ) -> grafeas.ListOccurrencesResponse: + """Post-rpc interceptor for list_occurrences + + DEPRECATED. Please use the `post_list_occurrences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_list_occurrences` interceptor runs + before the `post_list_occurrences_with_metadata` interceptor. + """ + return response + + def post_list_occurrences_with_metadata( + self, + response: grafeas.ListOccurrencesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.ListOccurrencesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_occurrences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_list_occurrences_with_metadata` + interceptor in new development instead of the `post_list_occurrences` interceptor. + When both interceptors are used, this `post_list_occurrences_with_metadata` interceptor runs after the + `post_list_occurrences` interceptor. The (possibly modified) response returned by + `post_list_occurrences` will be passed to + `post_list_occurrences_with_metadata`. + """ + return response, metadata + + def pre_update_note( + self, + request: grafeas.UpdateNoteRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.UpdateNoteRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_note + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_update_note(self, response: grafeas.Note) -> grafeas.Note: + """Post-rpc interceptor for update_note + + DEPRECATED. Please use the `post_update_note_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_update_note` interceptor runs + before the `post_update_note_with_metadata` interceptor. + """ + return response + + def post_update_note_with_metadata( + self, response: grafeas.Note, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[grafeas.Note, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_note + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_update_note_with_metadata` + interceptor in new development instead of the `post_update_note` interceptor. + When both interceptors are used, this `post_update_note_with_metadata` interceptor runs after the + `post_update_note` interceptor. The (possibly modified) response returned by + `post_update_note` will be passed to + `post_update_note_with_metadata`. + """ + return response, metadata + + def pre_update_occurrence( + self, + request: grafeas.UpdateOccurrenceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + grafeas.UpdateOccurrenceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the Grafeas server. + """ + return request, metadata + + def post_update_occurrence( + self, response: grafeas.Occurrence + ) -> grafeas.Occurrence: + """Post-rpc interceptor for update_occurrence + + DEPRECATED. Please use the `post_update_occurrence_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Grafeas server but before + it is returned to user code. This `post_update_occurrence` interceptor runs + before the `post_update_occurrence_with_metadata` interceptor. + """ + return response + + def post_update_occurrence_with_metadata( + self, + response: grafeas.Occurrence, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[grafeas.Occurrence, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_occurrence + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Grafeas server but before it is returned to user code. + + We recommend only using this `post_update_occurrence_with_metadata` + interceptor in new development instead of the `post_update_occurrence` interceptor. + When both interceptors are used, this `post_update_occurrence_with_metadata` interceptor runs after the + `post_update_occurrence` interceptor. The (possibly modified) response returned by + `post_update_occurrence` will be passed to + `post_update_occurrence_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class GrafeasRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GrafeasRestInterceptor + + +class GrafeasRestTransport(_BaseGrafeasRestTransport): + """REST backend synchronous transport for Grafeas. + + `Grafeas `__ API. + + Retrieves analysis results of Cloud components such as Docker + container images. + + Analysis results are stored as a series of occurrences. An + ``Occurrence`` contains information about a specific analysis + instance on a resource. An occurrence refers to a ``Note``. A note + contains details describing the analysis and is generally stored in + a separate project, called a ``Provider``. Multiple occurrences can + refer to the same note. + + For example, an SSL vulnerability could affect multiple images. In + this case, there would be one note for the vulnerability and an + occurrence for each image with the vulnerability referring to that + note. + + 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 = "", + 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[GrafeasRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: ''). + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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 + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GrafeasRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchCreateNotes( + _BaseGrafeasRestTransport._BaseBatchCreateNotes, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.BatchCreateNotes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: grafeas.BatchCreateNotesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateNotesResponse: + r"""Call the batch create notes method over HTTP. + + Args: + request (~.grafeas.BatchCreateNotesRequest): + The request object. Request to create notes in batch. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.BatchCreateNotesResponse: + Response for creating notes in batch. + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_create_notes( + request, metadata + ) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.BatchCreateNotes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._BatchCreateNotes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = grafeas.BatchCreateNotesResponse() + pb_resp = grafeas.BatchCreateNotesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_notes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_notes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.BatchCreateNotesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.batch_create_notes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchCreateOccurrences( + _BaseGrafeasRestTransport._BaseBatchCreateOccurrences, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.BatchCreateOccurrences") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: grafeas.BatchCreateOccurrencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.BatchCreateOccurrencesResponse: + r"""Call the batch create occurrences method over HTTP. + + Args: + request (~.grafeas.BatchCreateOccurrencesRequest): + The request object. Request to create occurrences in + batch. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.BatchCreateOccurrencesResponse: + Response for creating occurrences in + batch. + + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_create_occurrences( + request, metadata + ) + transcoded_request = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_transcoded_request( + http_options, request + ) + + body = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.BatchCreateOccurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._BatchCreateOccurrences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = grafeas.BatchCreateOccurrencesResponse() + pb_resp = grafeas.BatchCreateOccurrencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_occurrences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_occurrences_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.BatchCreateOccurrencesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.batch_create_occurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "BatchCreateOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateNote(_BaseGrafeasRestTransport._BaseCreateNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.CreateNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: grafeas.CreateNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Call the create note method over HTTP. + + Args: + request (~.grafeas.CreateNoteRequest): + The request object. Request to create a new note. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseCreateNote._get_http_options() + + request, metadata = self._interceptor.pre_create_note(request, metadata) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseCreateNote._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseGrafeasRestTransport._BaseCreateNote._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseCreateNote._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.CreateNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._CreateNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_note(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_note_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.create_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateOccurrence( + _BaseGrafeasRestTransport._BaseCreateOccurrence, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.CreateOccurrence") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: grafeas.CreateOccurrenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Call the create occurrence method over HTTP. + + Args: + request (~.grafeas.CreateOccurrenceRequest): + The request object. Request to create a new occurrence. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseCreateOccurrence._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_occurrence( + request, metadata + ) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseCreateOccurrence._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseGrafeasRestTransport._BaseCreateOccurrence._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseCreateOccurrence._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.CreateOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._CreateOccurrence._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = grafeas.Occurrence() + pb_resp = grafeas.Occurrence.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_occurrence(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_occurrence_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.create_occurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "CreateOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteNote(_BaseGrafeasRestTransport._BaseDeleteNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.DeleteNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.DeleteNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete note method over HTTP. + + Args: + request (~.grafeas.DeleteNoteRequest): + The request object. Request to delete a note. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseGrafeasRestTransport._BaseDeleteNote._get_http_options() + + request, metadata = self._interceptor.pre_delete_note(request, metadata) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseDeleteNote._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseDeleteNote._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.DeleteNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "DeleteNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._DeleteNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteOccurrence( + _BaseGrafeasRestTransport._BaseDeleteOccurrence, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.DeleteOccurrence") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.DeleteOccurrenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete occurrence method over HTTP. + + Args: + request (~.grafeas.DeleteOccurrenceRequest): + The request object. Request to delete an occurrence. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_occurrence( + request, metadata + ) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.DeleteOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "DeleteOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._DeleteOccurrence._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetNote(_BaseGrafeasRestTransport._BaseGetNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.GetNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.GetNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Call the get note method over HTTP. + + Args: + request (~.grafeas.GetNoteRequest): + The request object. Request to get a note. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseGetNote._get_http_options() + + request, metadata = self._interceptor.pre_get_note(request, metadata) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseGetNote._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseGetNote._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.GetNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._GetNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_note(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_note_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.get_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOccurrence(_BaseGrafeasRestTransport._BaseGetOccurrence, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.GetOccurrence") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.GetOccurrenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Call the get occurrence method over HTTP. + + Args: + request (~.grafeas.GetOccurrenceRequest): + The request object. Request to get an occurrence. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseGetOccurrence._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_occurrence(request, metadata) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseGetOccurrence._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseGetOccurrence._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.GetOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._GetOccurrence._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = grafeas.Occurrence() + pb_resp = grafeas.Occurrence.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_occurrence(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_occurrence_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.get_occurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOccurrenceNote( + _BaseGrafeasRestTransport._BaseGetOccurrenceNote, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.GetOccurrenceNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.GetOccurrenceNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Call the get occurrence note method over HTTP. + + Args: + request (~.grafeas.GetOccurrenceNoteRequest): + The request object. Request to get the note to which the + specified occurrence is attached. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_occurrence_note( + request, metadata + ) + transcoded_request = _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.GetOccurrenceNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrenceNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._GetOccurrenceNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_occurrence_note(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_occurrence_note_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.get_occurrence_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "GetOccurrenceNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListNoteOccurrences( + _BaseGrafeasRestTransport._BaseListNoteOccurrences, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.ListNoteOccurrences") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.ListNoteOccurrencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.ListNoteOccurrencesResponse: + r"""Call the list note occurrences method over HTTP. + + Args: + request (~.grafeas.ListNoteOccurrencesRequest): + The request object. Request to list occurrences for a + note. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.ListNoteOccurrencesResponse: + Response for listing occurrences for + a note. + + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_note_occurrences( + request, metadata + ) + transcoded_request = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.ListNoteOccurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNoteOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._ListNoteOccurrences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = grafeas.ListNoteOccurrencesResponse() + pb_resp = grafeas.ListNoteOccurrencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_note_occurrences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_note_occurrences_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.ListNoteOccurrencesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.list_note_occurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNoteOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListNotes(_BaseGrafeasRestTransport._BaseListNotes, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.ListNotes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.ListNotesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.ListNotesResponse: + r"""Call the list notes method over HTTP. + + Args: + request (~.grafeas.ListNotesRequest): + The request object. Request to list notes. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.ListNotesResponse: + Response for listing notes. + """ + + http_options = _BaseGrafeasRestTransport._BaseListNotes._get_http_options() + + request, metadata = self._interceptor.pre_list_notes(request, metadata) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseListNotes._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseListNotes._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.ListNotes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNotes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._ListNotes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = grafeas.ListNotesResponse() + pb_resp = grafeas.ListNotesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_notes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_notes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.ListNotesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.list_notes", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListNotes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOccurrences( + _BaseGrafeasRestTransport._BaseListOccurrences, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.ListOccurrences") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: grafeas.ListOccurrencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.ListOccurrencesResponse: + r"""Call the list occurrences method over HTTP. + + Args: + request (~.grafeas.ListOccurrencesRequest): + The request object. Request to list occurrences. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.ListOccurrencesResponse: + Response for listing occurrences. + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseListOccurrences._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_occurrences( + request, metadata + ) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseListOccurrences._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseListOccurrences._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.ListOccurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListOccurrences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._ListOccurrences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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 = grafeas.ListOccurrencesResponse() + pb_resp = grafeas.ListOccurrencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_occurrences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_occurrences_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.ListOccurrencesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.list_occurrences", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "ListOccurrences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateNote(_BaseGrafeasRestTransport._BaseUpdateNote, GrafeasRestStub): + def __hash__(self): + return hash("GrafeasRestTransport.UpdateNote") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: grafeas.UpdateNoteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Note: + r"""Call the update note method over HTTP. + + Args: + request (~.grafeas.UpdateNoteRequest): + The request object. Request to update a note. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Note: + A type of analysis that can be done + for a resource. + + """ + + http_options = _BaseGrafeasRestTransport._BaseUpdateNote._get_http_options() + + request, metadata = self._interceptor.pre_update_note(request, metadata) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseUpdateNote._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseGrafeasRestTransport._BaseUpdateNote._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseUpdateNote._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.UpdateNote", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateNote", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._UpdateNote._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = grafeas.Note() + pb_resp = grafeas.Note.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_note(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_note_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Note.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.update_note", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateNote", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateOccurrence( + _BaseGrafeasRestTransport._BaseUpdateOccurrence, GrafeasRestStub + ): + def __hash__(self): + return hash("GrafeasRestTransport.UpdateOccurrence") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: grafeas.UpdateOccurrenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> grafeas.Occurrence: + r"""Call the update occurrence method over HTTP. + + Args: + request (~.grafeas.UpdateOccurrenceRequest): + The request object. Request to update an occurrence. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.grafeas.Occurrence: + An instance of an analysis type that + has been found on a resource. + + """ + + http_options = ( + _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_occurrence( + request, metadata + ) + transcoded_request = ( + _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for grafeas_v1.GrafeasClient.UpdateOccurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateOccurrence", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GrafeasRestTransport._UpdateOccurrence._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = grafeas.Occurrence() + pb_resp = grafeas.Occurrence.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_occurrence(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_occurrence_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = grafeas.Occurrence.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for grafeas_v1.GrafeasClient.update_occurrence", + extra={ + "serviceName": "grafeas.v1.Grafeas", + "rpcName": "UpdateOccurrence", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_create_notes( + self, + ) -> Callable[[grafeas.BatchCreateNotesRequest], grafeas.BatchCreateNotesResponse]: + # 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._BatchCreateNotes(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_create_occurrences( + self, + ) -> Callable[ + [grafeas.BatchCreateOccurrencesRequest], grafeas.BatchCreateOccurrencesResponse + ]: + # 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._BatchCreateOccurrences(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_note(self) -> Callable[[grafeas.CreateNoteRequest], grafeas.Note]: + # 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._CreateNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_occurrence( + self, + ) -> Callable[[grafeas.CreateOccurrenceRequest], grafeas.Occurrence]: + # 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._CreateOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_note(self) -> Callable[[grafeas.DeleteNoteRequest], empty_pb2.Empty]: + # 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._DeleteNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_occurrence( + self, + ) -> Callable[[grafeas.DeleteOccurrenceRequest], empty_pb2.Empty]: + # 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._DeleteOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_note(self) -> Callable[[grafeas.GetNoteRequest], grafeas.Note]: + # 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._GetNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_occurrence( + self, + ) -> Callable[[grafeas.GetOccurrenceRequest], grafeas.Occurrence]: + # 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._GetOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_occurrence_note( + self, + ) -> Callable[[grafeas.GetOccurrenceNoteRequest], grafeas.Note]: + # 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._GetOccurrenceNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_note_occurrences( + self, + ) -> Callable[ + [grafeas.ListNoteOccurrencesRequest], grafeas.ListNoteOccurrencesResponse + ]: + # 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._ListNoteOccurrences(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notes( + self, + ) -> Callable[[grafeas.ListNotesRequest], grafeas.ListNotesResponse]: + # 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._ListNotes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_occurrences( + self, + ) -> Callable[[grafeas.ListOccurrencesRequest], grafeas.ListOccurrencesResponse]: + # 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._ListOccurrences(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_note(self) -> Callable[[grafeas.UpdateNoteRequest], grafeas.Note]: + # 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._UpdateNote(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_occurrence( + self, + ) -> Callable[[grafeas.UpdateOccurrenceRequest], grafeas.Occurrence]: + # 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._UpdateOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("GrafeasRestTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py new file mode 100644 index 000000000000..dd852b1d486b --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/services/grafeas/transports/rest_base.py @@ -0,0 +1,874 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from grafeas.grafeas_v1.types import grafeas + +from .base import DEFAULT_CLIENT_INFO, GrafeasTransport + + +class _BaseGrafeasRestTransport(GrafeasTransport): + """Base REST backend transport for Grafeas. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 = "containeranalysis.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'containeranalysis.googleapis.com'). + credentials (Optional[Any]): 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. + 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 + 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, + ) + + class _BaseBatchCreateNotes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/notes:batchCreate", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/notes:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.BatchCreateNotesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseBatchCreateNotes._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchCreateOccurrences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/occurrences:batchCreate", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/occurrences:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.BatchCreateOccurrencesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseBatchCreateOccurrences._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "noteId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/notes", + "body": "note", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/notes", + "body": "note", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.CreateNoteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseCreateNote._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateOccurrence: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/occurrences", + "body": "occurrence", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/occurrences", + "body": "occurrence", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.CreateOccurrenceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseCreateOccurrence._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/notes/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/notes/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.DeleteNoteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseDeleteNote._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOccurrence: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/occurrences/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/occurrences/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.DeleteOccurrenceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseDeleteOccurrence._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/notes/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/notes/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.GetNoteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseGetNote._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOccurrence: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/occurrences/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/occurrences/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.GetOccurrenceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseGetOccurrence._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOccurrenceNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/occurrences/*}/notes", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/occurrences/*}/notes", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.GetOccurrenceNoteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseGetOccurrenceNote._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListNoteOccurrences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/notes/*}/occurrences", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/notes/*}/occurrences", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.ListNoteOccurrencesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseListNoteOccurrences._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListNotes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/notes", + }, + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/notes", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.ListNotesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseListNotes._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListOccurrences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/occurrences", + }, + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/occurrences", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.ListOccurrencesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseListOccurrences._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateNote: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=projects/*/notes/*}", + "body": "note", + }, + { + "method": "patch", + "uri": "/v1/{name=projects/*/locations/*/notes/*}", + "body": "note", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.UpdateNoteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseUpdateNote._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateOccurrence: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=projects/*/occurrences/*}", + "body": "occurrence", + }, + { + "method": "patch", + "uri": "/v1/{name=projects/*/locations/*/occurrences/*}", + "body": "occurrence", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grafeas.UpdateOccurrenceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGrafeasRestTransport._BaseUpdateOccurrence._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseGrafeasRestTransport",) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/__init__.py b/packages/grafeas/grafeas/grafeas_v1/types/__init__.py new file mode 100644 index 000000000000..66635ba28b86 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/__init__.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 .attestation import AttestationNote, AttestationOccurrence, Jwt +from .build import BuildNote, BuildOccurrence +from .common import ( + BaseImage, + Digest, + Envelope, + EnvelopeSignature, + FileLocation, + LayerDetails, + License, + NoteKind, + RelatedUrl, + Signature, +) +from .compliance import ( + ComplianceNote, + ComplianceOccurrence, + ComplianceVersion, + NonCompliantFile, +) +from .cvss import CVSS, CVSSv3, CVSSVersion +from .deployment import DeploymentNote, DeploymentOccurrence +from .discovery import DiscoveryNote, DiscoveryOccurrence +from .dsse_attestation import DSSEAttestationNote, DSSEAttestationOccurrence +from .grafeas import ( + BatchCreateNotesRequest, + BatchCreateNotesResponse, + BatchCreateOccurrencesRequest, + BatchCreateOccurrencesResponse, + CreateNoteRequest, + CreateOccurrenceRequest, + DeleteNoteRequest, + DeleteOccurrenceRequest, + GetNoteRequest, + GetOccurrenceNoteRequest, + GetOccurrenceRequest, + ListNoteOccurrencesRequest, + ListNoteOccurrencesResponse, + ListNotesRequest, + ListNotesResponse, + ListOccurrencesRequest, + ListOccurrencesResponse, + Note, + Occurrence, + UpdateNoteRequest, + UpdateOccurrenceRequest, +) +from .image import Fingerprint, ImageNote, ImageOccurrence, Layer +from .intoto_provenance import ( + BuilderConfig, + Completeness, + InTotoProvenance, + Metadata, + Recipe, +) +from .intoto_statement import InTotoSlsaProvenanceV1, InTotoStatement, Subject +from .package import ( + Architecture, + Distribution, + Location, + PackageNote, + PackageOccurrence, + Version, +) +from .provenance import ( + AliasContext, + Artifact, + BuildProvenance, + CloudRepoSourceContext, + Command, + FileHashes, + GerritSourceContext, + GitSourceContext, + Hash, + ProjectRepoId, + RepoId, + Source, + SourceContext, +) +from .sbom import ( + SbomReferenceIntotoPayload, + SbomReferenceIntotoPredicate, + SBOMReferenceNote, + SBOMReferenceOccurrence, +) +from .secret import ( + SecretKind, + SecretLocation, + SecretNote, + SecretOccurrence, + SecretStatus, +) +from .severity import Severity +from .slsa_provenance import SlsaProvenance +from .slsa_provenance_zero_two import SlsaProvenanceZeroTwo +from .upgrade import UpgradeDistribution, UpgradeNote, UpgradeOccurrence, WindowsUpdate +from .vex import VulnerabilityAssessmentNote +from .vulnerability import VulnerabilityNote, VulnerabilityOccurrence + +__all__ = ( + "AttestationNote", + "AttestationOccurrence", + "Jwt", + "BuildNote", + "BuildOccurrence", + "BaseImage", + "Digest", + "Envelope", + "EnvelopeSignature", + "FileLocation", + "LayerDetails", + "License", + "RelatedUrl", + "Signature", + "NoteKind", + "ComplianceNote", + "ComplianceOccurrence", + "ComplianceVersion", + "NonCompliantFile", + "CVSS", + "CVSSv3", + "CVSSVersion", + "DeploymentNote", + "DeploymentOccurrence", + "DiscoveryNote", + "DiscoveryOccurrence", + "DSSEAttestationNote", + "DSSEAttestationOccurrence", + "BatchCreateNotesRequest", + "BatchCreateNotesResponse", + "BatchCreateOccurrencesRequest", + "BatchCreateOccurrencesResponse", + "CreateNoteRequest", + "CreateOccurrenceRequest", + "DeleteNoteRequest", + "DeleteOccurrenceRequest", + "GetNoteRequest", + "GetOccurrenceNoteRequest", + "GetOccurrenceRequest", + "ListNoteOccurrencesRequest", + "ListNoteOccurrencesResponse", + "ListNotesRequest", + "ListNotesResponse", + "ListOccurrencesRequest", + "ListOccurrencesResponse", + "Note", + "Occurrence", + "UpdateNoteRequest", + "UpdateOccurrenceRequest", + "Fingerprint", + "ImageNote", + "ImageOccurrence", + "Layer", + "BuilderConfig", + "Completeness", + "InTotoProvenance", + "Metadata", + "Recipe", + "InTotoSlsaProvenanceV1", + "InTotoStatement", + "Subject", + "Distribution", + "Location", + "PackageNote", + "PackageOccurrence", + "Version", + "Architecture", + "AliasContext", + "Artifact", + "BuildProvenance", + "CloudRepoSourceContext", + "Command", + "FileHashes", + "GerritSourceContext", + "GitSourceContext", + "Hash", + "ProjectRepoId", + "RepoId", + "Source", + "SourceContext", + "SbomReferenceIntotoPayload", + "SbomReferenceIntotoPredicate", + "SBOMReferenceNote", + "SBOMReferenceOccurrence", + "SecretLocation", + "SecretNote", + "SecretOccurrence", + "SecretStatus", + "SecretKind", + "Severity", + "SlsaProvenance", + "SlsaProvenanceZeroTwo", + "UpgradeDistribution", + "UpgradeNote", + "UpgradeOccurrence", + "WindowsUpdate", + "VulnerabilityAssessmentNote", + "VulnerabilityNote", + "VulnerabilityOccurrence", +) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/attestation.py b/packages/grafeas/grafeas/grafeas_v1/types/attestation.py new file mode 100644 index 000000000000..5d0229daac9c --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/attestation.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import common + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "AttestationNote", + "Jwt", + "AttestationOccurrence", + }, +) + + +class AttestationNote(proto.Message): + r"""Note kind that represents a logical attestation "role" or + "authority". For example, an organization might have one + ``Authority`` for "QA" and one for "build". This note is intended to + act strictly as a grouping mechanism for the attached occurrences + (Attestations). This grouping mechanism also provides a security + boundary, since IAM ACLs gate the ability for a principle to attach + an occurrence to a given note. It also provides a single point of + lookup to find all attached attestation occurrences, even if they + don't all live in the same project. + + Attributes: + hint (grafeas.grafeas_v1.types.AttestationNote.Hint): + Hint hints at the purpose of the attestation + authority. + """ + + class Hint(proto.Message): + r"""This submessage provides human-readable hints about the + purpose of the authority. Because the name of a note acts as its + resource reference, it is important to disambiguate the + canonical name of the Note (which might be a UUID for security + purposes) from "readable" names more suitable for debug output. + Note that these hints should not be used to look up authorities + in security sensitive contexts, such as when looking up + attestations to verify. + + Attributes: + human_readable_name (str): + Required. The human readable name of this + attestation authority, for example "qa". + """ + + human_readable_name: str = proto.Field( + proto.STRING, + number=1, + ) + + hint: Hint = proto.Field( + proto.MESSAGE, + number=1, + message=Hint, + ) + + +class Jwt(proto.Message): + r""" + + Attributes: + compact_jwt (str): + The compact encoding of a JWS, which is + always three base64 encoded strings joined by + periods. For details, see: + + https://tools.ietf.org/html/rfc7515.html#section-3.1 + """ + + compact_jwt: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AttestationOccurrence(proto.Message): + r"""Occurrence that represents a single "attestation". The + authenticity of an attestation can be verified using the + attached signature. If the verifier trusts the public key of the + signer, then verifying the signature is sufficient to establish + trust. In this circumstance, the authority to which this + attestation is attached is primarily useful for lookup (how to + find this attestation if you already know the authority and + artifact to be verified) and intent (for which authority this + attestation was intended to sign. + + Attributes: + serialized_payload (bytes): + Required. The serialized payload that is verified by one or + more ``signatures``. + signatures (MutableSequence[grafeas.grafeas_v1.types.Signature]): + One or more signatures over ``serialized_payload``. Verifier + implementations should consider this attestation message + verified if at least one ``signature`` verifies + ``serialized_payload``. See ``Signature`` in common.proto + for more details on signature structure and verification. + jwts (MutableSequence[grafeas.grafeas_v1.types.Jwt]): + One or more JWTs encoding a self-contained attestation. Each + JWT encodes the payload that it verifies within the JWT + itself. Verifier implementation SHOULD ignore the + ``serialized_payload`` field when verifying these JWTs. If + only JWTs are present on this AttestationOccurrence, then + the ``serialized_payload`` SHOULD be left empty. Each JWT + SHOULD encode a claim specific to the ``resource_uri`` of + this Occurrence, but this is not validated by Grafeas + metadata API implementations. The JWT itself is opaque to + Grafeas. + """ + + serialized_payload: bytes = proto.Field( + proto.BYTES, + number=1, + ) + signatures: MutableSequence[common.Signature] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Signature, + ) + jwts: MutableSequence["Jwt"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Jwt", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/build.py b/packages/grafeas/grafeas/grafeas_v1/types/build.py new file mode 100644 index 000000000000..837f08b2249e --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/build.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import intoto_provenance as g_intoto_provenance +from grafeas.grafeas_v1.types import intoto_statement as g_intoto_statement +from grafeas.grafeas_v1.types import provenance as g_provenance + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "BuildNote", + "BuildOccurrence", + }, +) + + +class BuildNote(proto.Message): + r"""Note holding the version of the provider's builder and the + signature of the provenance message in the build details + occurrence. + + Attributes: + builder_version (str): + Required. Immutable. Version of the builder + which produced this build. + """ + + builder_version: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BuildOccurrence(proto.Message): + r"""Details of a build occurrence. + + Attributes: + provenance (grafeas.grafeas_v1.types.BuildProvenance): + The actual provenance for the build. + provenance_bytes (str): + Serialized JSON representation of the provenance, used in + generating the build signature in the corresponding build + note. After verifying the signature, ``provenance_bytes`` + can be unmarshalled and compared to the provenance to + confirm that it is unchanged. A base64-encoded string + representation of the provenance bytes is used for the + signature in order to interoperate with openssl which + expects this format for signature verification. + + The serialized form is captured both to avoid ambiguity in + how the provenance is marshalled to json as well to prevent + incompatibilities with future changes. + intoto_provenance (grafeas.grafeas_v1.types.InTotoProvenance): + Deprecated. See InTotoStatement for the + replacement. In-toto Provenance representation + as defined in spec. + intoto_statement (grafeas.grafeas_v1.types.InTotoStatement): + In-toto Statement representation as defined in spec. The + intoto_statement can contain any type of provenance. The + serialized payload of the statement can be stored and signed + in the Occurrence's envelope. + in_toto_slsa_provenance_v1 (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1): + In-Toto Slsa Provenance V1 represents a slsa + provenance meeting the slsa spec, wrapped in an + in-toto statement. This allows for direct + jsonification of a to-spec in-toto slsa + statement with a to-spec slsa provenance. + """ + + provenance: g_provenance.BuildProvenance = proto.Field( + proto.MESSAGE, + number=1, + message=g_provenance.BuildProvenance, + ) + provenance_bytes: str = proto.Field( + proto.STRING, + number=2, + ) + intoto_provenance: g_intoto_provenance.InTotoProvenance = proto.Field( + proto.MESSAGE, + number=3, + message=g_intoto_provenance.InTotoProvenance, + ) + intoto_statement: g_intoto_statement.InTotoStatement = proto.Field( + proto.MESSAGE, + number=4, + message=g_intoto_statement.InTotoStatement, + ) + in_toto_slsa_provenance_v1: g_intoto_statement.InTotoSlsaProvenanceV1 = proto.Field( + proto.MESSAGE, + number=5, + message=g_intoto_statement.InTotoSlsaProvenanceV1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/common.py b/packages/grafeas/grafeas/grafeas_v1/types/common.py new file mode 100644 index 000000000000..45d9b9e23c13 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/common.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "NoteKind", + "RelatedUrl", + "Signature", + "Envelope", + "EnvelopeSignature", + "FileLocation", + "BaseImage", + "LayerDetails", + "License", + "Digest", + }, +) + + +class NoteKind(proto.Enum): + r"""Kind represents the kinds of notes supported. + + Values: + NOTE_KIND_UNSPECIFIED (0): + Default value. This value is unused. + VULNERABILITY (1): + The note and occurrence represent a package + vulnerability. + BUILD (2): + The note and occurrence assert build + provenance. + IMAGE (3): + This represents an image basis relationship. + PACKAGE (4): + This represents a package installed via a + package manager. + DEPLOYMENT (5): + The note and occurrence track deployment + events. + DISCOVERY (6): + The note and occurrence track the initial + discovery status of a resource. + ATTESTATION (7): + This represents a logical "role" that can + attest to artifacts. + UPGRADE (8): + This represents an available package upgrade. + COMPLIANCE (9): + This represents a Compliance Note + DSSE_ATTESTATION (10): + This represents a DSSE attestation Note + VULNERABILITY_ASSESSMENT (11): + This represents a Vulnerability Assessment. + SBOM_REFERENCE (12): + This represents an SBOM Reference. + SECRET (13): + This represents a secret. + """ + NOTE_KIND_UNSPECIFIED = 0 + VULNERABILITY = 1 + BUILD = 2 + IMAGE = 3 + PACKAGE = 4 + DEPLOYMENT = 5 + DISCOVERY = 6 + ATTESTATION = 7 + UPGRADE = 8 + COMPLIANCE = 9 + DSSE_ATTESTATION = 10 + VULNERABILITY_ASSESSMENT = 11 + SBOM_REFERENCE = 12 + SECRET = 13 + + +class RelatedUrl(proto.Message): + r"""Metadata for any related URL information. + + Attributes: + url (str): + Specific URL associated with the resource. + label (str): + Label to describe usage of the URL. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Signature(proto.Message): + r"""Verifiers (e.g. Kritis implementations) MUST verify signatures with + respect to the trust anchors defined in policy (e.g. a Kritis + policy). Typically this means that the verifier has been configured + with a map from ``public_key_id`` to public key material (and any + required parameters, e.g. signing algorithm). + + In particular, verification implementations MUST NOT treat the + signature ``public_key_id`` as anything more than a key lookup hint. + The ``public_key_id`` DOES NOT validate or authenticate a public + key; it only provides a mechanism for quickly selecting a public key + ALREADY CONFIGURED on the verifier through a trusted channel. + Verification implementations MUST reject signatures in any of the + following circumstances: + + - The ``public_key_id`` is not recognized by the verifier. + - The public key that ``public_key_id`` refers to does not verify + the signature with respect to the payload. + + The ``signature`` contents SHOULD NOT be "attached" (where the + payload is included with the serialized ``signature`` bytes). + Verifiers MUST ignore any "attached" payload and only verify + signatures with respect to explicitly provided payload (e.g. a + ``payload`` field on the proto message that holds this Signature, or + the canonical serialization of the proto message that holds this + signature). + + Attributes: + signature (bytes): + The content of the signature, an opaque + bytestring. The payload that this signature + verifies MUST be unambiguously provided with the + Signature during verification. A wrapper message + might provide the payload explicitly. + Alternatively, a message might have a canonical + serialization that can always be unambiguously + computed to derive the payload. + public_key_id (str): + The identifier for the public key that verifies this + signature. + + - The ``public_key_id`` is required. + - The ``public_key_id`` SHOULD be an RFC3986 conformant URI. + - When possible, the ``public_key_id`` SHOULD be an + immutable reference, such as a cryptographic digest. + + Examples of valid ``public_key_id``\ s: + + OpenPGP V4 public key fingerprint: + + - "openpgp4fpr:74FAF3B861BDA0870C7B6DEF607E48D2A663AEEA" See + https://www.iana.org/assignments/uri-schemes/prov/openpgp4fpr + for more details on this scheme. + + RFC6920 digest-named SubjectPublicKeyInfo (digest of the DER + serialization): + + - "ni:///sha-256;cD9o9Cq6LG3jD0iKXqEi_vdjJGecm_iXkbqVoScViaU" + - "nih:///sha-256;703f68f42aba2c6de30f488a5ea122fef76324679c9bf89791ba95a1271589a5". + """ + + signature: bytes = proto.Field( + proto.BYTES, + number=1, + ) + public_key_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Envelope(proto.Message): + r"""MUST match + https://github.com/secure-systems-lab/dsse/blob/master/envelope.proto. + An authenticated message of arbitrary type. + + Attributes: + payload (bytes): + + payload_type (str): + + signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): + + """ + + payload: bytes = proto.Field( + proto.BYTES, + number=1, + ) + payload_type: str = proto.Field( + proto.STRING, + number=2, + ) + signatures: MutableSequence["EnvelopeSignature"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="EnvelopeSignature", + ) + + +class EnvelopeSignature(proto.Message): + r""" + + Attributes: + sig (bytes): + + keyid (str): + + """ + + sig: bytes = proto.Field( + proto.BYTES, + number=1, + ) + keyid: str = proto.Field( + proto.STRING, + number=2, + ) + + +class FileLocation(proto.Message): + r"""Indicates the location at which a package was found. + + Attributes: + file_path (str): + For jars that are contained inside .war + files, this filepath can indicate the path to + war file combined with the path to jar file. + layer_details (grafeas.grafeas_v1.types.LayerDetails): + Each package found in a file should have its + own layer metadata (that is, information from + the origin layer of the package). + """ + + file_path: str = proto.Field( + proto.STRING, + number=1, + ) + layer_details: "LayerDetails" = proto.Field( + proto.MESSAGE, + number=2, + message="LayerDetails", + ) + + +class BaseImage(proto.Message): + r"""BaseImage describes a base image of a container image. + + Attributes: + name (str): + The name of the base image. + repository (str): + The repository name in which the base image + is from. + layer_count (int): + The number of layers that the base image is + composed of. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + repository: str = proto.Field( + proto.STRING, + number=2, + ) + layer_count: int = proto.Field( + proto.INT32, + number=3, + ) + + +class LayerDetails(proto.Message): + r"""Details about the layer a package was found in. + + Attributes: + index (int): + The index of the layer in the container + image. + diff_id (str): + The diff ID (typically a sha256 hash) of the + layer in the container image. + chain_id (str): + The layer chain ID (sha256 hash) of the layer + in the container image. + https://github.com/opencontainers/image-spec/blob/main/config.md#layer-chainid + command (str): + The layer build command that was used to + build the layer. This may not be found in all + layers depending on how the container image is + built. + base_images (MutableSequence[grafeas.grafeas_v1.types.BaseImage]): + The base images the layer is found within. + """ + + index: int = proto.Field( + proto.INT32, + number=1, + ) + diff_id: str = proto.Field( + proto.STRING, + number=2, + ) + chain_id: str = proto.Field( + proto.STRING, + number=5, + ) + command: str = proto.Field( + proto.STRING, + number=3, + ) + base_images: MutableSequence["BaseImage"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="BaseImage", + ) + + +class License(proto.Message): + r"""License information. + + Attributes: + expression (str): + Often a single license can be used to + represent the licensing terms. Sometimes it is + necessary to include a choice of one or more + licenses or some combination of license + identifiers. + Examples: "LGPL-2.1-only OR MIT", "LGPL-2.1-only + AND MIT", "GPL-2.0-or-later WITH + Bison-exception-2.2". + comments (str): + Comments + """ + + expression: str = proto.Field( + proto.STRING, + number=1, + ) + comments: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Digest(proto.Message): + r"""Digest information. + + Attributes: + algo (str): + ``SHA1``, ``SHA512`` etc. + digest_bytes (bytes): + Value of the digest. + """ + + algo: str = proto.Field( + proto.STRING, + number=1, + ) + digest_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/compliance.py b/packages/grafeas/grafeas/grafeas_v1/types/compliance.py new file mode 100644 index 000000000000..5cd9cb5fd59f --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/compliance.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import severity as g_severity + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "ComplianceNote", + "ComplianceVersion", + "ComplianceOccurrence", + "NonCompliantFile", + }, +) + + +class ComplianceNote(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + title (str): + The title that identifies this compliance + check. + description (str): + A description about this compliance check. + version (MutableSequence[grafeas.grafeas_v1.types.ComplianceVersion]): + The OS and config versions the benchmark + applies to. + rationale (str): + A rationale for the existence of this + compliance check. + remediation (str): + A description of remediation steps if the + compliance check fails. + cis_benchmark (grafeas.grafeas_v1.types.ComplianceNote.CisBenchmark): + + This field is a member of `oneof`_ ``compliance_type``. + scan_instructions (bytes): + Serialized scan instructions with a + predefined format. + impact (str): + + This field is a member of `oneof`_ ``potential_impact``. + """ + + class CisBenchmark(proto.Message): + r"""A compliance check that is a CIS benchmark. + + Attributes: + profile_level (int): + + severity (grafeas.grafeas_v1.types.Severity): + + """ + + profile_level: int = proto.Field( + proto.INT32, + number=1, + ) + severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=2, + enum=g_severity.Severity, + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + version: MutableSequence["ComplianceVersion"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="ComplianceVersion", + ) + rationale: str = proto.Field( + proto.STRING, + number=4, + ) + remediation: str = proto.Field( + proto.STRING, + number=5, + ) + cis_benchmark: CisBenchmark = proto.Field( + proto.MESSAGE, + number=6, + oneof="compliance_type", + message=CisBenchmark, + ) + scan_instructions: bytes = proto.Field( + proto.BYTES, + number=7, + ) + impact: str = proto.Field( + proto.STRING, + number=8, + oneof="potential_impact", + ) + + +class ComplianceVersion(proto.Message): + r"""Describes the CIS benchmark version that is applicable to a + given OS and os version. + + Attributes: + cpe_uri (str): + The CPE URI + (https://cpe.mitre.org/specification/) this + benchmark is applicable to. + benchmark_document (str): + The name of the document that defines this + benchmark, e.g. "CIS Container-Optimized OS". + version (str): + The version of the benchmark. This is set to + the version of the OS-specific CIS document the + benchmark is defined in. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + benchmark_document: str = proto.Field( + proto.STRING, + number=3, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ComplianceOccurrence(proto.Message): + r"""An indication that the compliance checks in the associated + ComplianceNote were not satisfied for particular resources or a + specified reason. + + Attributes: + non_compliant_files (MutableSequence[grafeas.grafeas_v1.types.NonCompliantFile]): + + non_compliance_reason (str): + + version (grafeas.grafeas_v1.types.ComplianceVersion): + The OS and config version the benchmark was + run on. + """ + + non_compliant_files: MutableSequence["NonCompliantFile"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="NonCompliantFile", + ) + non_compliance_reason: str = proto.Field( + proto.STRING, + number=3, + ) + version: "ComplianceVersion" = proto.Field( + proto.MESSAGE, + number=4, + message="ComplianceVersion", + ) + + +class NonCompliantFile(proto.Message): + r"""Details about files that caused a compliance check to fail. + + Attributes: + path (str): + Empty if ``display_command`` is set. + display_command (str): + Command to display the non-compliant files. + reason (str): + Explains why a file is non compliant for a + CIS check. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + display_command: str = proto.Field( + proto.STRING, + number=2, + ) + reason: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/cvss.py b/packages/grafeas/grafeas/grafeas_v1/types/cvss.py new file mode 100644 index 000000000000..68c78c55c516 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/cvss.py @@ -0,0 +1,465 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "CVSSVersion", + "CVSSv3", + "CVSS", + }, +) + + +class CVSSVersion(proto.Enum): + r"""CVSS Version. + + Values: + CVSS_VERSION_UNSPECIFIED (0): + No description available. + CVSS_VERSION_2 (1): + No description available. + CVSS_VERSION_3 (2): + No description available. + """ + CVSS_VERSION_UNSPECIFIED = 0 + CVSS_VERSION_2 = 1 + CVSS_VERSION_3 = 2 + + +class CVSSv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + For details, see + https://www.first.org/cvss/specification-document + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + exploitability_score (float): + + impact_score (float): + + attack_vector (grafeas.grafeas_v1.types.CVSSv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. + attack_complexity (grafeas.grafeas_v1.types.CVSSv3.AttackComplexity): + + privileges_required (grafeas.grafeas_v1.types.CVSSv3.PrivilegesRequired): + + user_interaction (grafeas.grafeas_v1.types.CVSSv3.UserInteraction): + + scope (grafeas.grafeas_v1.types.CVSSv3.Scope): + + confidentiality_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + integrity_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + availability_impact (grafeas.grafeas_v1.types.CVSSv3.Impact): + + """ + + class AttackVector(proto.Enum): + r""" + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + No description available. + ATTACK_VECTOR_NETWORK (1): + No description available. + ATTACK_VECTOR_ADJACENT (2): + No description available. + ATTACK_VECTOR_LOCAL (3): + No description available. + ATTACK_VECTOR_PHYSICAL (4): + No description available. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r""" + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + No description available. + ATTACK_COMPLEXITY_LOW (1): + No description available. + ATTACK_COMPLEXITY_HIGH (2): + No description available. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r""" + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + No description available. + PRIVILEGES_REQUIRED_NONE (1): + No description available. + PRIVILEGES_REQUIRED_LOW (2): + No description available. + PRIVILEGES_REQUIRED_HIGH (3): + No description available. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r""" + + Values: + USER_INTERACTION_UNSPECIFIED (0): + No description available. + USER_INTERACTION_NONE (1): + No description available. + USER_INTERACTION_REQUIRED (2): + No description available. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r""" + + Values: + SCOPE_UNSPECIFIED (0): + No description available. + SCOPE_UNCHANGED (1): + No description available. + SCOPE_CHANGED (2): + No description available. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r""" + + Values: + IMPACT_UNSPECIFIED (0): + No description available. + IMPACT_HIGH (1): + No description available. + IMPACT_LOW (2): + No description available. + IMPACT_NONE (3): + No description available. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + exploitability_score: float = proto.Field( + proto.FLOAT, + number=2, + ) + impact_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=5, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=6, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +class CVSS(proto.Message): + r"""Common Vulnerability Scoring System. + For details, see + https://www.first.org/cvss/specification-document This is a + message we will try to use for storing various versions of CVSS + rather than making a separate proto for storing a specific + version. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + exploitability_score (float): + + impact_score (float): + + attack_vector (grafeas.grafeas_v1.types.CVSS.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. + attack_complexity (grafeas.grafeas_v1.types.CVSS.AttackComplexity): + + authentication (grafeas.grafeas_v1.types.CVSS.Authentication): + + privileges_required (grafeas.grafeas_v1.types.CVSS.PrivilegesRequired): + + user_interaction (grafeas.grafeas_v1.types.CVSS.UserInteraction): + + scope (grafeas.grafeas_v1.types.CVSS.Scope): + + confidentiality_impact (grafeas.grafeas_v1.types.CVSS.Impact): + + integrity_impact (grafeas.grafeas_v1.types.CVSS.Impact): + + availability_impact (grafeas.grafeas_v1.types.CVSS.Impact): + + """ + + class AttackVector(proto.Enum): + r""" + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + No description available. + ATTACK_VECTOR_NETWORK (1): + No description available. + ATTACK_VECTOR_ADJACENT (2): + No description available. + ATTACK_VECTOR_LOCAL (3): + No description available. + ATTACK_VECTOR_PHYSICAL (4): + No description available. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r""" + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + No description available. + ATTACK_COMPLEXITY_LOW (1): + No description available. + ATTACK_COMPLEXITY_HIGH (2): + No description available. + ATTACK_COMPLEXITY_MEDIUM (3): + No description available. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + ATTACK_COMPLEXITY_MEDIUM = 3 + + class Authentication(proto.Enum): + r""" + + Values: + AUTHENTICATION_UNSPECIFIED (0): + No description available. + AUTHENTICATION_MULTIPLE (1): + No description available. + AUTHENTICATION_SINGLE (2): + No description available. + AUTHENTICATION_NONE (3): + No description available. + """ + AUTHENTICATION_UNSPECIFIED = 0 + AUTHENTICATION_MULTIPLE = 1 + AUTHENTICATION_SINGLE = 2 + AUTHENTICATION_NONE = 3 + + class PrivilegesRequired(proto.Enum): + r""" + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + No description available. + PRIVILEGES_REQUIRED_NONE (1): + No description available. + PRIVILEGES_REQUIRED_LOW (2): + No description available. + PRIVILEGES_REQUIRED_HIGH (3): + No description available. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r""" + + Values: + USER_INTERACTION_UNSPECIFIED (0): + No description available. + USER_INTERACTION_NONE (1): + No description available. + USER_INTERACTION_REQUIRED (2): + No description available. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r""" + + Values: + SCOPE_UNSPECIFIED (0): + No description available. + SCOPE_UNCHANGED (1): + No description available. + SCOPE_CHANGED (2): + No description available. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r""" + + Values: + IMPACT_UNSPECIFIED (0): + No description available. + IMPACT_HIGH (1): + No description available. + IMPACT_LOW (2): + No description available. + IMPACT_NONE (3): + No description available. + IMPACT_PARTIAL (4): + No description available. + IMPACT_COMPLETE (5): + No description available. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + IMPACT_PARTIAL = 4 + IMPACT_COMPLETE = 5 + + base_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + exploitability_score: float = proto.Field( + proto.FLOAT, + number=2, + ) + impact_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=4, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=5, + enum=AttackComplexity, + ) + authentication: Authentication = proto.Field( + proto.ENUM, + number=6, + enum=Authentication, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/deployment.py b/packages/grafeas/grafeas/grafeas_v1/types/deployment.py new file mode 100644 index 000000000000..9d41a4aa7764 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/deployment.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "DeploymentNote", + "DeploymentOccurrence", + }, +) + + +class DeploymentNote(proto.Message): + r"""An artifact that can be deployed in some runtime. + + Attributes: + resource_uri (MutableSequence[str]): + Required. Resource URI for the artifact being + deployed. + """ + + resource_uri: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class DeploymentOccurrence(proto.Message): + r"""The period during which some deployable was active in a + runtime. + + Attributes: + user_email (str): + Identity of the user that triggered this + deployment. + deploy_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Beginning of the lifetime of this + deployment. + undeploy_time (google.protobuf.timestamp_pb2.Timestamp): + End of the lifetime of this deployment. + config (str): + Configuration used to create this deployment. + address (str): + Address of the runtime element hosting this + deployment. + resource_uri (MutableSequence[str]): + Output only. Resource URI for the artifact + being deployed taken from the deployable field + with the same name. + platform (grafeas.grafeas_v1.types.DeploymentOccurrence.Platform): + Platform hosting this deployment. + """ + + class Platform(proto.Enum): + r"""Types of platforms. + + Values: + PLATFORM_UNSPECIFIED (0): + Unknown. + GKE (1): + Google Container Engine. + FLEX (2): + Google App Engine: Flexible Environment. + CUSTOM (3): + Custom user-defined platform. + """ + PLATFORM_UNSPECIFIED = 0 + GKE = 1 + FLEX = 2 + CUSTOM = 3 + + user_email: str = proto.Field( + proto.STRING, + number=1, + ) + deploy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + undeploy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + config: str = proto.Field( + proto.STRING, + number=4, + ) + address: str = proto.Field( + proto.STRING, + number=5, + ) + resource_uri: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + platform: Platform = proto.Field( + proto.ENUM, + number=7, + enum=Platform, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/discovery.py b/packages/grafeas/grafeas/grafeas_v1/types/discovery.py new file mode 100644 index 000000000000..9a6b9d17c47e --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/discovery.py @@ -0,0 +1,283 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import common + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "DiscoveryNote", + "DiscoveryOccurrence", + }, +) + + +class DiscoveryNote(proto.Message): + r"""A note that indicates a type of analysis a provider would perform. + This note exists in a provider's project. A ``Discovery`` occurrence + is created in a consumer's project at the start of analysis. + + Attributes: + analysis_kind (grafeas.grafeas_v1.types.NoteKind): + Required. Immutable. The kind of analysis + that is handled by this discovery. + """ + + analysis_kind: common.NoteKind = proto.Field( + proto.ENUM, + number=1, + enum=common.NoteKind, + ) + + +class DiscoveryOccurrence(proto.Message): + r"""Provides information about the analysis status of a + discovered resource. + + Attributes: + continuous_analysis (grafeas.grafeas_v1.types.DiscoveryOccurrence.ContinuousAnalysis): + Whether the resource is continuously + analyzed. + analysis_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisStatus): + The status of discovery for the resource. + analysis_completed (grafeas.grafeas_v1.types.DiscoveryOccurrence.AnalysisCompleted): + + analysis_error (MutableSequence[google.rpc.status_pb2.Status]): + Indicates any errors encountered during + analysis of a resource. There could be 0 or more + of these errors. + analysis_status_error (google.rpc.status_pb2.Status): + When an error is encountered this will + contain a LocalizedMessage under details to show + to the user. The LocalizedMessage is output only + and populated by the API. + cpe (str): + The CPE of the resource being scanned. + last_scan_time (google.protobuf.timestamp_pb2.Timestamp): + The last time this resource was scanned. + archive_time (google.protobuf.timestamp_pb2.Timestamp): + The time occurrences related to this + discovery occurrence were archived. + sbom_status (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus): + The status of an SBOM generation. + vulnerability_attestation (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation): + The status of an vulnerability attestation + generation. + """ + + class ContinuousAnalysis(proto.Enum): + r"""Whether the resource is continuously analyzed. + + Values: + CONTINUOUS_ANALYSIS_UNSPECIFIED (0): + Unknown. + ACTIVE (1): + The resource is continuously analyzed. + INACTIVE (2): + The resource is ignored for continuous + analysis. + """ + CONTINUOUS_ANALYSIS_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class AnalysisStatus(proto.Enum): + r"""Analysis status for a resource. Currently for initial + analysis only (not updated in continuous analysis). + + Values: + ANALYSIS_STATUS_UNSPECIFIED (0): + Unknown. + PENDING (1): + Resource is known but no action has been + taken yet. + SCANNING (2): + Resource is being analyzed. + FINISHED_SUCCESS (3): + Analysis has finished successfully. + COMPLETE (3): + Analysis has completed. + FINISHED_FAILED (4): + Analysis has finished unsuccessfully, the + analysis itself is in a bad state. + FINISHED_UNSUPPORTED (5): + The resource is known not to be supported. + """ + _pb_options = {"allow_alias": True} + ANALYSIS_STATUS_UNSPECIFIED = 0 + PENDING = 1 + SCANNING = 2 + FINISHED_SUCCESS = 3 + COMPLETE = 3 + FINISHED_FAILED = 4 + FINISHED_UNSUPPORTED = 5 + + class AnalysisCompleted(proto.Message): + r"""Indicates which analysis completed successfully. Multiple + types of analysis can be performed on a single resource. + + Attributes: + analysis_type (MutableSequence[str]): + + """ + + analysis_type: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class SBOMStatus(proto.Message): + r"""The status of an SBOM generation. + + Attributes: + sbom_state (grafeas.grafeas_v1.types.DiscoveryOccurrence.SBOMStatus.SBOMState): + The progress of the SBOM generation. + error (str): + If there was an error generating an SBOM, + this will indicate what that error was. + """ + + class SBOMState(proto.Enum): + r"""An enum indicating the progress of the SBOM generation. + + Values: + SBOM_STATE_UNSPECIFIED (0): + Default unknown state. + PENDING (1): + SBOM scanning is pending. + COMPLETE (2): + SBOM scanning has completed. + """ + SBOM_STATE_UNSPECIFIED = 0 + PENDING = 1 + COMPLETE = 2 + + sbom_state: "DiscoveryOccurrence.SBOMStatus.SBOMState" = proto.Field( + proto.ENUM, + number=1, + enum="DiscoveryOccurrence.SBOMStatus.SBOMState", + ) + error: str = proto.Field( + proto.STRING, + number=2, + ) + + class VulnerabilityAttestation(proto.Message): + r"""The status of an vulnerability attestation generation. + + Attributes: + last_attempt_time (google.protobuf.timestamp_pb2.Timestamp): + The last time we attempted to generate an + attestation. + state (grafeas.grafeas_v1.types.DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState): + The success/failure state of the latest + attestation attempt. + error (str): + If failure, the error reason for why the + attestation generation failed. + """ + + class VulnerabilityAttestationState(proto.Enum): + r"""An enum indicating the state of the attestation generation. + + Values: + VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED (0): + Default unknown state. + SUCCESS (1): + Attestation was successfully generated and + stored. + FAILURE (2): + Attestation was unsuccessfully generated and + stored. + """ + VULNERABILITY_ATTESTATION_STATE_UNSPECIFIED = 0 + SUCCESS = 1 + FAILURE = 2 + + last_attempt_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + state: "DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState" = proto.Field( + proto.ENUM, + number=2, + enum="DiscoveryOccurrence.VulnerabilityAttestation.VulnerabilityAttestationState", + ) + error: str = proto.Field( + proto.STRING, + number=3, + ) + + continuous_analysis: ContinuousAnalysis = proto.Field( + proto.ENUM, + number=1, + enum=ContinuousAnalysis, + ) + analysis_status: AnalysisStatus = proto.Field( + proto.ENUM, + number=2, + enum=AnalysisStatus, + ) + analysis_completed: AnalysisCompleted = proto.Field( + proto.MESSAGE, + number=7, + message=AnalysisCompleted, + ) + analysis_error: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=status_pb2.Status, + ) + analysis_status_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + cpe: str = proto.Field( + proto.STRING, + number=4, + ) + last_scan_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + archive_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + sbom_status: SBOMStatus = proto.Field( + proto.MESSAGE, + number=9, + message=SBOMStatus, + ) + vulnerability_attestation: VulnerabilityAttestation = proto.Field( + proto.MESSAGE, + number=10, + message=VulnerabilityAttestation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py b/packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py new file mode 100644 index 000000000000..5d3ca5c2c750 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/dsse_attestation.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import common, intoto_statement + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "DSSEAttestationNote", + "DSSEAttestationOccurrence", + }, +) + + +class DSSEAttestationNote(proto.Message): + r""" + + Attributes: + hint (grafeas.grafeas_v1.types.DSSEAttestationNote.DSSEHint): + DSSEHint hints at the purpose of the + attestation authority. + """ + + class DSSEHint(proto.Message): + r"""This submessage provides human-readable hints about the + purpose of the authority. Because the name of a note acts as its + resource reference, it is important to disambiguate the + canonical name of the Note (which might be a UUID for security + purposes) from "readable" names more suitable for debug output. + Note that these hints should not be used to look up authorities + in security sensitive contexts, such as when looking up + attestations to verify. + + Attributes: + human_readable_name (str): + Required. The human readable name of this + attestation authority, for example + "cloudbuild-prod". + """ + + human_readable_name: str = proto.Field( + proto.STRING, + number=1, + ) + + hint: DSSEHint = proto.Field( + proto.MESSAGE, + number=1, + message=DSSEHint, + ) + + +class DSSEAttestationOccurrence(proto.Message): + r"""Deprecated. Prefer to use a regular Occurrence, and populate + the Envelope at the top level of the Occurrence. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + envelope (grafeas.grafeas_v1.types.Envelope): + If doing something security critical, make + sure to verify the signatures in this metadata. + statement (grafeas.grafeas_v1.types.InTotoStatement): + + This field is a member of `oneof`_ ``decoded_payload``. + """ + + envelope: common.Envelope = proto.Field( + proto.MESSAGE, + number=1, + message=common.Envelope, + ) + statement: intoto_statement.InTotoStatement = proto.Field( + proto.MESSAGE, + number=2, + oneof="decoded_payload", + message=intoto_statement.InTotoStatement, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/grafeas.py b/packages/grafeas/grafeas/grafeas_v1/types/grafeas.py new file mode 100644 index 000000000000..b23a2a679a9b --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/grafeas.py @@ -0,0 +1,941 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import attestation as g_attestation +from grafeas.grafeas_v1.types import build as g_build +from grafeas.grafeas_v1.types import common +from grafeas.grafeas_v1.types import compliance as g_compliance +from grafeas.grafeas_v1.types import deployment as g_deployment +from grafeas.grafeas_v1.types import discovery as g_discovery +from grafeas.grafeas_v1.types import dsse_attestation as g_dsse_attestation +from grafeas.grafeas_v1.types import image as g_image +from grafeas.grafeas_v1.types import package as g_package +from grafeas.grafeas_v1.types import sbom +from grafeas.grafeas_v1.types import secret as g_secret +from grafeas.grafeas_v1.types import upgrade as g_upgrade +from grafeas.grafeas_v1.types import vex +from grafeas.grafeas_v1.types import vulnerability as g_vulnerability + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "Occurrence", + "Note", + "GetOccurrenceRequest", + "ListOccurrencesRequest", + "ListOccurrencesResponse", + "DeleteOccurrenceRequest", + "CreateOccurrenceRequest", + "UpdateOccurrenceRequest", + "GetNoteRequest", + "GetOccurrenceNoteRequest", + "ListNotesRequest", + "ListNotesResponse", + "DeleteNoteRequest", + "CreateNoteRequest", + "UpdateNoteRequest", + "ListNoteOccurrencesRequest", + "ListNoteOccurrencesResponse", + "BatchCreateNotesRequest", + "BatchCreateNotesResponse", + "BatchCreateOccurrencesRequest", + "BatchCreateOccurrencesResponse", + }, +) + + +class Occurrence(proto.Message): + r"""An instance of an analysis type that has been found on a + resource. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + resource_uri (str): + Required. Immutable. A URI that represents the resource for + which the occurrence applies. For example, + ``https://gcr.io/project/image@sha256:123abc`` for a Docker + image. + note_name (str): + Required. Immutable. The analysis note associated with this + occurrence, in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. This field can + be used as a filter in list requests. + kind (grafeas.grafeas_v1.types.NoteKind): + Output only. This explicitly denotes which of + the occurrence details are specified. This field + can be used as a filter in list requests. + remediation (str): + A description of actions that can be taken to + remedy the note. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this occurrence was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this occurrence was + last updated. + vulnerability (grafeas.grafeas_v1.types.VulnerabilityOccurrence): + Describes a security vulnerability. + + This field is a member of `oneof`_ ``details``. + build (grafeas.grafeas_v1.types.BuildOccurrence): + Describes a verifiable build. + + This field is a member of `oneof`_ ``details``. + image (grafeas.grafeas_v1.types.ImageOccurrence): + Describes how this resource derives from the + basis in the associated note. + + This field is a member of `oneof`_ ``details``. + package (grafeas.grafeas_v1.types.PackageOccurrence): + Describes the installation of a package on + the linked resource. + + This field is a member of `oneof`_ ``details``. + deployment (grafeas.grafeas_v1.types.DeploymentOccurrence): + Describes the deployment of an artifact on a + runtime. + + This field is a member of `oneof`_ ``details``. + discovery (grafeas.grafeas_v1.types.DiscoveryOccurrence): + Describes when a resource was discovered. + + This field is a member of `oneof`_ ``details``. + attestation (grafeas.grafeas_v1.types.AttestationOccurrence): + Describes an attestation of an artifact. + + This field is a member of `oneof`_ ``details``. + upgrade (grafeas.grafeas_v1.types.UpgradeOccurrence): + Describes an available package upgrade on the + linked resource. + + This field is a member of `oneof`_ ``details``. + compliance (grafeas.grafeas_v1.types.ComplianceOccurrence): + Describes a compliance violation on a linked + resource. + + This field is a member of `oneof`_ ``details``. + dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationOccurrence): + Describes an attestation of an artifact using + dsse. + + This field is a member of `oneof`_ ``details``. + sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceOccurrence): + Describes a specific SBOM reference + occurrences. + + This field is a member of `oneof`_ ``details``. + secret (grafeas.grafeas_v1.types.SecretOccurrence): + Describes a secret. + + This field is a member of `oneof`_ ``details``. + envelope (grafeas.grafeas_v1.types.Envelope): + https://github.com/secure-systems-lab/dsse + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_uri: str = proto.Field( + proto.STRING, + number=2, + ) + note_name: str = proto.Field( + proto.STRING, + number=3, + ) + kind: common.NoteKind = proto.Field( + proto.ENUM, + number=4, + enum=common.NoteKind, + ) + remediation: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + vulnerability: g_vulnerability.VulnerabilityOccurrence = proto.Field( + proto.MESSAGE, + number=8, + oneof="details", + message=g_vulnerability.VulnerabilityOccurrence, + ) + build: g_build.BuildOccurrence = proto.Field( + proto.MESSAGE, + number=9, + oneof="details", + message=g_build.BuildOccurrence, + ) + image: g_image.ImageOccurrence = proto.Field( + proto.MESSAGE, + number=10, + oneof="details", + message=g_image.ImageOccurrence, + ) + package: g_package.PackageOccurrence = proto.Field( + proto.MESSAGE, + number=11, + oneof="details", + message=g_package.PackageOccurrence, + ) + deployment: g_deployment.DeploymentOccurrence = proto.Field( + proto.MESSAGE, + number=12, + oneof="details", + message=g_deployment.DeploymentOccurrence, + ) + discovery: g_discovery.DiscoveryOccurrence = proto.Field( + proto.MESSAGE, + number=13, + oneof="details", + message=g_discovery.DiscoveryOccurrence, + ) + attestation: g_attestation.AttestationOccurrence = proto.Field( + proto.MESSAGE, + number=14, + oneof="details", + message=g_attestation.AttestationOccurrence, + ) + upgrade: g_upgrade.UpgradeOccurrence = proto.Field( + proto.MESSAGE, + number=15, + oneof="details", + message=g_upgrade.UpgradeOccurrence, + ) + compliance: g_compliance.ComplianceOccurrence = proto.Field( + proto.MESSAGE, + number=16, + oneof="details", + message=g_compliance.ComplianceOccurrence, + ) + dsse_attestation: g_dsse_attestation.DSSEAttestationOccurrence = proto.Field( + proto.MESSAGE, + number=17, + oneof="details", + message=g_dsse_attestation.DSSEAttestationOccurrence, + ) + sbom_reference: sbom.SBOMReferenceOccurrence = proto.Field( + proto.MESSAGE, + number=19, + oneof="details", + message=sbom.SBOMReferenceOccurrence, + ) + secret: g_secret.SecretOccurrence = proto.Field( + proto.MESSAGE, + number=20, + oneof="details", + message=g_secret.SecretOccurrence, + ) + envelope: common.Envelope = proto.Field( + proto.MESSAGE, + number=18, + message=common.Envelope, + ) + + +class Note(proto.Message): + r"""A type of analysis that can be done for a resource. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + short_description (str): + A one sentence description of this note. + long_description (str): + A detailed description of this note. + kind (grafeas.grafeas_v1.types.NoteKind): + Output only. The type of analysis. This field + can be used as a filter in list requests. + related_url (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + URLs associated with this note. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Time of expiration for this note. Empty if + note does not expire. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this note was created. + This field can be used as a filter in list + requests. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this note was last + updated. This field can be used as a filter in + list requests. + related_note_names (MutableSequence[str]): + Other notes related to this note. + vulnerability (grafeas.grafeas_v1.types.VulnerabilityNote): + A note describing a package vulnerability. + + This field is a member of `oneof`_ ``type``. + build (grafeas.grafeas_v1.types.BuildNote): + A note describing build provenance for a + verifiable build. + + This field is a member of `oneof`_ ``type``. + image (grafeas.grafeas_v1.types.ImageNote): + A note describing a base image. + + This field is a member of `oneof`_ ``type``. + package (grafeas.grafeas_v1.types.PackageNote): + A note describing a package hosted by various + package managers. + + This field is a member of `oneof`_ ``type``. + deployment (grafeas.grafeas_v1.types.DeploymentNote): + A note describing something that can be + deployed. + + This field is a member of `oneof`_ ``type``. + discovery (grafeas.grafeas_v1.types.DiscoveryNote): + A note describing the initial analysis of a + resource. + + This field is a member of `oneof`_ ``type``. + attestation (grafeas.grafeas_v1.types.AttestationNote): + A note describing an attestation role. + + This field is a member of `oneof`_ ``type``. + upgrade (grafeas.grafeas_v1.types.UpgradeNote): + A note describing available package upgrades. + + This field is a member of `oneof`_ ``type``. + compliance (grafeas.grafeas_v1.types.ComplianceNote): + A note describing a compliance check. + + This field is a member of `oneof`_ ``type``. + dsse_attestation (grafeas.grafeas_v1.types.DSSEAttestationNote): + A note describing a dsse attestation note. + + This field is a member of `oneof`_ ``type``. + vulnerability_assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote): + A note describing a vulnerability assessment. + + This field is a member of `oneof`_ ``type``. + sbom_reference (grafeas.grafeas_v1.types.SBOMReferenceNote): + A note describing an SBOM reference. + + This field is a member of `oneof`_ ``type``. + secret (grafeas.grafeas_v1.types.SecretNote): + A note describing a secret. + + This field is a member of `oneof`_ ``type``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + short_description: str = proto.Field( + proto.STRING, + number=2, + ) + long_description: str = proto.Field( + proto.STRING, + number=3, + ) + kind: common.NoteKind = proto.Field( + proto.ENUM, + number=4, + enum=common.NoteKind, + ) + related_url: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=common.RelatedUrl, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + related_note_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + vulnerability: g_vulnerability.VulnerabilityNote = proto.Field( + proto.MESSAGE, + number=10, + oneof="type", + message=g_vulnerability.VulnerabilityNote, + ) + build: g_build.BuildNote = proto.Field( + proto.MESSAGE, + number=11, + oneof="type", + message=g_build.BuildNote, + ) + image: g_image.ImageNote = proto.Field( + proto.MESSAGE, + number=12, + oneof="type", + message=g_image.ImageNote, + ) + package: g_package.PackageNote = proto.Field( + proto.MESSAGE, + number=13, + oneof="type", + message=g_package.PackageNote, + ) + deployment: g_deployment.DeploymentNote = proto.Field( + proto.MESSAGE, + number=14, + oneof="type", + message=g_deployment.DeploymentNote, + ) + discovery: g_discovery.DiscoveryNote = proto.Field( + proto.MESSAGE, + number=15, + oneof="type", + message=g_discovery.DiscoveryNote, + ) + attestation: g_attestation.AttestationNote = proto.Field( + proto.MESSAGE, + number=16, + oneof="type", + message=g_attestation.AttestationNote, + ) + upgrade: g_upgrade.UpgradeNote = proto.Field( + proto.MESSAGE, + number=17, + oneof="type", + message=g_upgrade.UpgradeNote, + ) + compliance: g_compliance.ComplianceNote = proto.Field( + proto.MESSAGE, + number=18, + oneof="type", + message=g_compliance.ComplianceNote, + ) + dsse_attestation: g_dsse_attestation.DSSEAttestationNote = proto.Field( + proto.MESSAGE, + number=19, + oneof="type", + message=g_dsse_attestation.DSSEAttestationNote, + ) + vulnerability_assessment: vex.VulnerabilityAssessmentNote = proto.Field( + proto.MESSAGE, + number=20, + oneof="type", + message=vex.VulnerabilityAssessmentNote, + ) + sbom_reference: sbom.SBOMReferenceNote = proto.Field( + proto.MESSAGE, + number=21, + oneof="type", + message=sbom.SBOMReferenceNote, + ) + secret: g_secret.SecretNote = proto.Field( + proto.MESSAGE, + number=22, + oneof="type", + message=g_secret.SecretNote, + ) + + +class GetOccurrenceRequest(proto.Message): + r"""Request to get an occurrence. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOccurrencesRequest(proto.Message): + r"""Request to list occurrences. + + Attributes: + parent (str): + The name of the project to list occurrences for in the form + of ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of occurrences to return in the list. + Must be positive. Max allowed page size is 1000. + If not specified, page size defaults to 20. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListOccurrencesResponse(proto.Message): + r"""Response for listing occurrences. + + Attributes: + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences requested. + next_page_token (str): + The next pagination token in the list response. It should be + used as ``page_token`` for the following request. An empty + value means no more results. + """ + + @property + def raw_page(self): + return self + + occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Occurrence", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteOccurrenceRequest(proto.Message): + r"""Request to delete an occurrence. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateOccurrenceRequest(proto.Message): + r"""Request to create a new occurrence. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrence is to + be created. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The occurrence to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + occurrence: "Occurrence" = proto.Field( + proto.MESSAGE, + number=2, + message="Occurrence", + ) + + +class UpdateOccurrenceRequest(proto.Message): + r"""Request to update an occurrence. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + occurrence (grafeas.grafeas_v1.types.Occurrence): + The updated occurrence. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + occurrence: "Occurrence" = proto.Field( + proto.MESSAGE, + number=2, + message="Occurrence", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class GetNoteRequest(proto.Message): + r"""Request to get a note. + + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOccurrenceNoteRequest(proto.Message): + r"""Request to get the note to which the specified occurrence is + attached. + + Attributes: + name (str): + The name of the occurrence in the form of + ``projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListNotesRequest(proto.Message): + r"""Request to list notes. + + Attributes: + parent (str): + The name of the project to list notes for in the form of + ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of notes to return in the list. Must + be positive. Max allowed page size is 1000. If + not specified, page size defaults to 20. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListNotesResponse(proto.Message): + r"""Response for listing notes. + + Attributes: + notes (MutableSequence[grafeas.grafeas_v1.types.Note]): + The notes requested. + next_page_token (str): + The next pagination token in the list response. It should be + used as ``page_token`` for the following request. An empty + value means no more results. + """ + + @property + def raw_page(self): + return self + + notes: MutableSequence["Note"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Note", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteNoteRequest(proto.Message): + r"""Request to delete a note. + + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateNoteRequest(proto.Message): + r"""Request to create a new note. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the note is to be + created. + note_id (str): + The ID to use for this note. + note (grafeas.grafeas_v1.types.Note): + The note to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + note_id: str = proto.Field( + proto.STRING, + number=2, + ) + note: "Note" = proto.Field( + proto.MESSAGE, + number=3, + message="Note", + ) + + +class UpdateNoteRequest(proto.Message): + r"""Request to update a note. + + Attributes: + name (str): + The name of the note in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + note (grafeas.grafeas_v1.types.Note): + The updated note. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields to update. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + note: "Note" = proto.Field( + proto.MESSAGE, + number=2, + message="Note", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ListNoteOccurrencesRequest(proto.Message): + r"""Request to list occurrences for a note. + + Attributes: + name (str): + The name of the note to list occurrences for in the form of + ``projects/[PROVIDER_ID]/notes/[NOTE_ID]``. + filter (str): + The filter expression. + page_size (int): + Number of occurrences to return in the list. + page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListNoteOccurrencesResponse(proto.Message): + r"""Response for listing occurrences for a note. + + Attributes: + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences attached to the specified + note. + next_page_token (str): + Token to provide to skip to a particular spot + in the list. + """ + + @property + def raw_page(self): + return self + + occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Occurrence", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchCreateNotesRequest(proto.Message): + r"""Request to create notes in batch. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the notes are to be + created. + notes (MutableMapping[str, grafeas.grafeas_v1.types.Note]): + The notes to create. Max allowed length is + 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + notes: MutableMapping[str, "Note"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="Note", + ) + + +class BatchCreateNotesResponse(proto.Message): + r"""Response for creating notes in batch. + + Attributes: + notes (MutableSequence[grafeas.grafeas_v1.types.Note]): + The notes that were created. + """ + + notes: MutableSequence["Note"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Note", + ) + + +class BatchCreateOccurrencesRequest(proto.Message): + r"""Request to create occurrences in batch. + + Attributes: + parent (str): + The name of the project in the form of + ``projects/[PROJECT_ID]``, under which the occurrences are + to be created. + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences to create. Max allowed length + is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Occurrence", + ) + + +class BatchCreateOccurrencesResponse(proto.Message): + r"""Response for creating occurrences in batch. + + Attributes: + occurrences (MutableSequence[grafeas.grafeas_v1.types.Occurrence]): + The occurrences that were created. + """ + + occurrences: MutableSequence["Occurrence"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Occurrence", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/image.py b/packages/grafeas/grafeas/grafeas_v1/types/image.py new file mode 100644 index 000000000000..f316aad20caf --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/image.py @@ -0,0 +1,157 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "Layer", + "Fingerprint", + "ImageNote", + "ImageOccurrence", + }, +) + + +class Layer(proto.Message): + r"""Layer holds metadata specific to a layer of a Docker image. + + Attributes: + directive (str): + Required. The recovered Dockerfile directive + used to construct this layer. See + https://docs.docker.com/engine/reference/builder/ + for more information. + arguments (str): + The recovered arguments to the Dockerfile + directive. + """ + + directive: str = proto.Field( + proto.STRING, + number=1, + ) + arguments: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Fingerprint(proto.Message): + r"""A set of properties that uniquely identify a given Docker + image. + + Attributes: + v1_name (str): + Required. The layer ID of the final layer in + the Docker image's v1 representation. + v2_blob (MutableSequence[str]): + Required. The ordered list of v2 blobs that + represent a given image. + v2_name (str): + Output only. The name of the image's v2 blobs computed via: + [bottom] := v2_blob[bottom] [N] := sha256(v2_blob[N] + " " + + v2_name[N+1]) Only the name of the final blob is kept. + """ + + v1_name: str = proto.Field( + proto.STRING, + number=1, + ) + v2_blob: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + v2_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ImageNote(proto.Message): + r"""Basis describes the base image portion (Note) of the DockerImage + relationship. Linked occurrences are derived from this or an + equivalent image via: FROM Or an equivalent + reference, e.g., a tag of the resource_url. + + Attributes: + resource_url (str): + Required. Immutable. The resource_url for the resource + representing the basis of associated occurrence images. + fingerprint (grafeas.grafeas_v1.types.Fingerprint): + Required. Immutable. The fingerprint of the + base image. + """ + + resource_url: str = proto.Field( + proto.STRING, + number=1, + ) + fingerprint: "Fingerprint" = proto.Field( + proto.MESSAGE, + number=2, + message="Fingerprint", + ) + + +class ImageOccurrence(proto.Message): + r"""Details of the derived image portion of the DockerImage + relationship. This image would be produced from a Dockerfile + with FROM . + + Attributes: + fingerprint (grafeas.grafeas_v1.types.Fingerprint): + Required. The fingerprint of the derived + image. + distance (int): + Output only. The number of layers by which + this image differs from the associated image + basis. + layer_info (MutableSequence[grafeas.grafeas_v1.types.Layer]): + This contains layer-specific metadata, if populated it has + length "distance" and is ordered with [distance] being the + layer immediately following the base image and [1] being the + final layer. + base_resource_url (str): + Output only. This contains the base image URL + for the derived image occurrence. + """ + + fingerprint: "Fingerprint" = proto.Field( + proto.MESSAGE, + number=1, + message="Fingerprint", + ) + distance: int = proto.Field( + proto.INT32, + number=2, + ) + layer_info: MutableSequence["Layer"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Layer", + ) + base_resource_url: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py b/packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py new file mode 100644 index 000000000000..08112fbc7e8e --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/intoto_provenance.py @@ -0,0 +1,246 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "Recipe", + "Completeness", + "Metadata", + "BuilderConfig", + "InTotoProvenance", + }, +) + + +class Recipe(proto.Message): + r"""Steps taken to build the artifact. + For a TaskRun, typically each container corresponds to one step + in the recipe. + + Attributes: + type_ (str): + URI indicating what type of recipe was + performed. It determines the meaning of + recipe.entryPoint, recipe.arguments, + recipe.environment, and materials. + defined_in_material (int): + Index in materials containing the recipe + steps that are not implied by recipe.type. For + example, if the recipe type were "make", then + this would point to the source containing the + Makefile, not the make program itself. Set to -1 + if the recipe doesn't come from a material, as + zero is default unset value for int64. + entry_point (str): + String identifying the entry point into the + build. This is often a path to a configuration + file and/or a target label within that file. The + syntax and meaning are defined by recipe.type. + For example, if the recipe type were "make", + then this would reference the directory in which + to run make as well as which target to use. + arguments (MutableSequence[google.protobuf.any_pb2.Any]): + Collection of all external inputs that + influenced the build on top of + recipe.definedInMaterial and recipe.entryPoint. + For example, if the recipe type were "make", + then this might be the flags passed to make + aside from the target, which is captured in + recipe.entryPoint. Since the arguments field can + greatly vary in structure, depending on the + builder and recipe type, this is of form "Any". + environment (MutableSequence[google.protobuf.any_pb2.Any]): + Any other builder-controlled inputs necessary + for correctly evaluating the recipe. Usually + only needed for reproducing the build but not + evaluated as part of policy. Since the + environment field can greatly vary in structure, + depending on the builder and recipe type, this + is of form "Any". + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + defined_in_material: int = proto.Field( + proto.INT64, + number=2, + ) + entry_point: str = proto.Field( + proto.STRING, + number=3, + ) + arguments: MutableSequence[any_pb2.Any] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=any_pb2.Any, + ) + environment: MutableSequence[any_pb2.Any] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=any_pb2.Any, + ) + + +class Completeness(proto.Message): + r"""Indicates that the builder claims certain fields in this + message to be complete. + + Attributes: + arguments (bool): + If true, the builder claims that + recipe.arguments is complete, meaning that all + external inputs are properly captured in the + recipe. + environment (bool): + If true, the builder claims that + recipe.environment is claimed to be complete. + materials (bool): + If true, the builder claims that materials + are complete, usually through some controls to + prevent network access. Sometimes called + "hermetic". + """ + + arguments: bool = proto.Field( + proto.BOOL, + number=1, + ) + environment: bool = proto.Field( + proto.BOOL, + number=2, + ) + materials: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Metadata(proto.Message): + r"""Other properties of the build. + + Attributes: + build_invocation_id (str): + Identifies the particular build invocation, + which can be useful for finding associated logs + or other ad-hoc analysis. The value SHOULD be + globally unique, per in-toto Provenance spec. + build_started_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build started. + build_finished_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build completed. + completeness (grafeas.grafeas_v1.types.Completeness): + Indicates that the builder claims certain + fields in this message to be complete. + reproducible (bool): + If true, the builder claims that running the + recipe on materials will produce bit-for-bit + identical output. + """ + + build_invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + build_started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + build_finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completeness: "Completeness" = proto.Field( + proto.MESSAGE, + number=4, + message="Completeness", + ) + reproducible: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class BuilderConfig(proto.Message): + r""" + + Attributes: + id (str): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InTotoProvenance(proto.Message): + r""" + + Attributes: + builder_config (grafeas.grafeas_v1.types.BuilderConfig): + required + recipe (grafeas.grafeas_v1.types.Recipe): + Identifies the configuration used for the + build. When combined with materials, this SHOULD + fully describe the build, such that re-running + this recipe results in bit-for-bit identical + output (if the build is reproducible). + metadata (grafeas.grafeas_v1.types.Metadata): + + materials (MutableSequence[str]): + The collection of artifacts that influenced + the build including sources, dependencies, build + tools, base images, and so on. This is + considered to be incomplete unless + metadata.completeness.materials is true. Unset + or null is equivalent to empty. + """ + + builder_config: "BuilderConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="BuilderConfig", + ) + recipe: "Recipe" = proto.Field( + proto.MESSAGE, + number=2, + message="Recipe", + ) + metadata: "Metadata" = proto.Field( + proto.MESSAGE, + number=3, + message="Metadata", + ) + materials: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py b/packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py new file mode 100644 index 000000000000..be85f5a36643 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/intoto_statement.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import ( + slsa_provenance_zero_two as g_slsa_provenance_zero_two, +) +from grafeas.grafeas_v1.types import intoto_provenance +from grafeas.grafeas_v1.types import slsa_provenance as g_slsa_provenance + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "InTotoStatement", + "Subject", + "InTotoSlsaProvenanceV1", + }, +) + + +class InTotoStatement(proto.Message): + r"""Spec defined at + https://github.com/in-toto/attestation/tree/main/spec#statement + The serialized InTotoStatement will be stored as + Envelope.payload. Envelope.payloadType is always + "application/vnd.in-toto+json". + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (str): + Always ``https://in-toto.io/Statement/v0.1``. + subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): + + predicate_type (str): + ``https://slsa.dev/provenance/v0.1`` for SlsaProvenance. + provenance (grafeas.grafeas_v1.types.InTotoProvenance): + + This field is a member of `oneof`_ ``predicate``. + slsa_provenance (grafeas.grafeas_v1.types.SlsaProvenance): + + This field is a member of `oneof`_ ``predicate``. + slsa_provenance_zero_two (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo): + + This field is a member of `oneof`_ ``predicate``. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + subject: MutableSequence["Subject"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Subject", + ) + predicate_type: str = proto.Field( + proto.STRING, + number=3, + ) + provenance: intoto_provenance.InTotoProvenance = proto.Field( + proto.MESSAGE, + number=4, + oneof="predicate", + message=intoto_provenance.InTotoProvenance, + ) + slsa_provenance: g_slsa_provenance.SlsaProvenance = proto.Field( + proto.MESSAGE, + number=5, + oneof="predicate", + message=g_slsa_provenance.SlsaProvenance, + ) + slsa_provenance_zero_two: g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo = ( + proto.Field( + proto.MESSAGE, + number=6, + oneof="predicate", + message=g_slsa_provenance_zero_two.SlsaProvenanceZeroTwo, + ) + ) + + +class Subject(proto.Message): + r""" + + Attributes: + name (str): + + digest (MutableMapping[str, str]): + ``"": ""`` Algorithms can be e.g. + sha256, sha512 See + https://github.com/in-toto/attestation/blob/main/spec/field_types.md#DigestSet + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class InTotoSlsaProvenanceV1(proto.Message): + r""" + + Attributes: + type_ (str): + InToto spec defined at + https://github.com/in-toto/attestation/tree/main/spec#statement + subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): + + predicate_type (str): + + predicate (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.SlsaProvenanceV1): + + """ + + class SlsaProvenanceV1(proto.Message): + r"""Keep in sync with schema at + https://github.com/slsa-framework/slsa/blob/main/docs/provenance/schema/v1/provenance.proto + Builder renamed to ProvenanceBuilder because of Java conflicts. + + Attributes: + build_definition (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildDefinition): + + run_details (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.RunDetails): + + """ + + build_definition: "InTotoSlsaProvenanceV1.BuildDefinition" = proto.Field( + proto.MESSAGE, + number=1, + message="InTotoSlsaProvenanceV1.BuildDefinition", + ) + run_details: "InTotoSlsaProvenanceV1.RunDetails" = proto.Field( + proto.MESSAGE, + number=2, + message="InTotoSlsaProvenanceV1.RunDetails", + ) + + class BuildDefinition(proto.Message): + r""" + + Attributes: + build_type (str): + + external_parameters (google.protobuf.struct_pb2.Struct): + + internal_parameters (google.protobuf.struct_pb2.Struct): + + resolved_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): + + """ + + build_type: str = proto.Field( + proto.STRING, + number=1, + ) + external_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + internal_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + resolved_dependencies: MutableSequence[ + "InTotoSlsaProvenanceV1.ResourceDescriptor" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="InTotoSlsaProvenanceV1.ResourceDescriptor", + ) + + class ResourceDescriptor(proto.Message): + r""" + + Attributes: + name (str): + + uri (str): + + digest (MutableMapping[str, str]): + + content (bytes): + + download_location (str): + + media_type (str): + + annotations (MutableMapping[str, google.protobuf.struct_pb2.Value]): + + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + content: bytes = proto.Field( + proto.BYTES, + number=4, + ) + download_location: str = proto.Field( + proto.STRING, + number=5, + ) + media_type: str = proto.Field( + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + + class RunDetails(proto.Message): + r""" + + Attributes: + builder (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ProvenanceBuilder): + + metadata (grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.BuildMetadata): + + byproducts (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): + + """ + + builder: "InTotoSlsaProvenanceV1.ProvenanceBuilder" = proto.Field( + proto.MESSAGE, + number=1, + message="InTotoSlsaProvenanceV1.ProvenanceBuilder", + ) + metadata: "InTotoSlsaProvenanceV1.BuildMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="InTotoSlsaProvenanceV1.BuildMetadata", + ) + byproducts: MutableSequence[ + "InTotoSlsaProvenanceV1.ResourceDescriptor" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="InTotoSlsaProvenanceV1.ResourceDescriptor", + ) + + class ProvenanceBuilder(proto.Message): + r""" + + Attributes: + id (str): + + version (MutableMapping[str, str]): + + builder_dependencies (MutableSequence[grafeas.grafeas_v1.types.InTotoSlsaProvenanceV1.ResourceDescriptor]): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + version: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + builder_dependencies: MutableSequence[ + "InTotoSlsaProvenanceV1.ResourceDescriptor" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="InTotoSlsaProvenanceV1.ResourceDescriptor", + ) + + class BuildMetadata(proto.Message): + r""" + + Attributes: + invocation_id (str): + + started_on (google.protobuf.timestamp_pb2.Timestamp): + + finished_on (google.protobuf.timestamp_pb2.Timestamp): + + """ + + invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + subject: MutableSequence["Subject"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Subject", + ) + predicate_type: str = proto.Field( + proto.STRING, + number=3, + ) + predicate: SlsaProvenanceV1 = proto.Field( + proto.MESSAGE, + number=4, + message=SlsaProvenanceV1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/package.py b/packages/grafeas/grafeas/grafeas_v1/types/package.py new file mode 100644 index 000000000000..7af0773ef0fc --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/package.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import common + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "Architecture", + "Distribution", + "Location", + "PackageNote", + "PackageOccurrence", + "Version", + }, +) + + +class Architecture(proto.Enum): + r"""Instruction set architectures supported by various package + managers. + + Values: + ARCHITECTURE_UNSPECIFIED (0): + Unknown architecture. + X86 (1): + X86 architecture. + X64 (2): + X64 architecture. + """ + ARCHITECTURE_UNSPECIFIED = 0 + X86 = 1 + X64 = 2 + + +class Distribution(proto.Message): + r"""This represents a particular channel of distribution for a + given package. E.g., Debian's jessie-backports dpkg mirror. + + Attributes: + cpe_uri (str): + The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + latest_version (grafeas.grafeas_v1.types.Version): + The latest available version of this package + in this distribution channel. + maintainer (str): + A freeform string denoting the maintainer of + this package. + url (str): + The distribution channel-specific homepage + for this package. + description (str): + The distribution channel-specific description + of this package. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + architecture: "Architecture" = proto.Field( + proto.ENUM, + number=2, + enum="Architecture", + ) + latest_version: "Version" = proto.Field( + proto.MESSAGE, + number=3, + message="Version", + ) + maintainer: str = proto.Field( + proto.STRING, + number=4, + ) + url: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + + +class Location(proto.Message): + r"""An occurrence of a particular package installation found within a + system's filesystem. E.g., glibc was found in + ``/var/lib/dpkg/status``. + + Attributes: + cpe_uri (str): + Deprecated. The CPE URI in `CPE + format `__ + version (grafeas.grafeas_v1.types.Version): + Deprecated. + The version installed at this location. + path (str): + The path from which we gathered that this + package/version is installed. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + version: "Version" = proto.Field( + proto.MESSAGE, + number=2, + message="Version", + ) + path: str = proto.Field( + proto.STRING, + number=3, + ) + + +class PackageNote(proto.Message): + r"""PackageNote represents a particular package version. + + Attributes: + name (str): + The name of the package. + distribution (MutableSequence[grafeas.grafeas_v1.types.Distribution]): + Deprecated. + The various channels by which a package is + distributed. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + cpe_uri (str): + The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. The + cpe_uri will be blank for language packages. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + Architecture will be blank for language + packages. + version (grafeas.grafeas_v1.types.Version): + The version of the package. + maintainer (str): + A freeform text denoting the maintainer of + this package. + url (str): + The homepage for this package. + description (str): + The description of this package. + license_ (grafeas.grafeas_v1.types.License): + Licenses that have been declared by the + authors of the package. + digest (MutableSequence[grafeas.grafeas_v1.types.Digest]): + Hash value, typically a file digest, that + allows unique identification a specific package. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + distribution: MutableSequence["Distribution"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="Distribution", + ) + package_type: str = proto.Field( + proto.STRING, + number=11, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=12, + ) + architecture: "Architecture" = proto.Field( + proto.ENUM, + number=13, + enum="Architecture", + ) + version: "Version" = proto.Field( + proto.MESSAGE, + number=14, + message="Version", + ) + maintainer: str = proto.Field( + proto.STRING, + number=15, + ) + url: str = proto.Field( + proto.STRING, + number=16, + ) + description: str = proto.Field( + proto.STRING, + number=17, + ) + license_: common.License = proto.Field( + proto.MESSAGE, + number=18, + message=common.License, + ) + digest: MutableSequence[common.Digest] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=common.Digest, + ) + + +class PackageOccurrence(proto.Message): + r"""Details on how a particular software package was installed on + a system. + + Attributes: + name (str): + The name of the installed package. + location (MutableSequence[grafeas.grafeas_v1.types.Location]): + All of the places within the filesystem + versions of this package have been found. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + cpe_uri (str): + The cpe_uri in `CPE + format `__ denoting + the package manager version distributing a package. The + cpe_uri will be blank for language packages. + architecture (grafeas.grafeas_v1.types.Architecture): + The CPU architecture for which packages in + this distribution channel were built. + Architecture will be blank for language + packages. + license_ (grafeas.grafeas_v1.types.License): + Licenses that have been declared by the + authors of the package. + version (grafeas.grafeas_v1.types.Version): + The version of the package. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + location: MutableSequence["Location"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Location", + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=4, + ) + architecture: "Architecture" = proto.Field( + proto.ENUM, + number=5, + enum="Architecture", + ) + license_: common.License = proto.Field( + proto.MESSAGE, + number=6, + message=common.License, + ) + version: "Version" = proto.Field( + proto.MESSAGE, + number=7, + message="Version", + ) + + +class Version(proto.Message): + r"""Version contains structured information about the version of + a package. + + Attributes: + epoch (int): + Used to correct mistakes in the version + numbering scheme. + name (str): + Required only when version kind is NORMAL. + The main part of the version name. + revision (str): + The iteration of the package build from the + above version. + inclusive (bool): + Whether this version is specifying part of an + inclusive range. Grafeas does not have the + capability to specify version ranges; instead we + have fields that specify start version and end + versions. At times this is insufficient - we + also need to specify whether the version is + included in the range or is excluded from the + range. This boolean is expected to be set to + true when the version is included in a range. + kind (grafeas.grafeas_v1.types.Version.VersionKind): + Required. Distinguishes between sentinel + MIN/MAX versions and normal versions. + full_name (str): + Human readable version string. This string is + of the form :- and is + only set when kind is NORMAL. + """ + + class VersionKind(proto.Enum): + r"""Whether this is an ordinary package version or a sentinel + MIN/MAX version. + + Values: + VERSION_KIND_UNSPECIFIED (0): + Unknown. + NORMAL (1): + A standard package version. + MINIMUM (2): + A special version representing negative + infinity. + MAXIMUM (3): + A special version representing positive + infinity. + """ + VERSION_KIND_UNSPECIFIED = 0 + NORMAL = 1 + MINIMUM = 2 + MAXIMUM = 3 + + epoch: int = proto.Field( + proto.INT32, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + revision: str = proto.Field( + proto.STRING, + number=3, + ) + inclusive: bool = proto.Field( + proto.BOOL, + number=6, + ) + kind: VersionKind = proto.Field( + proto.ENUM, + number=4, + enum=VersionKind, + ) + full_name: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/provenance.py b/packages/grafeas/grafeas/grafeas_v1/types/provenance.py new file mode 100644 index 000000000000..35ee483a7b6b --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/provenance.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "BuildProvenance", + "Source", + "FileHashes", + "Hash", + "Command", + "Artifact", + "SourceContext", + "AliasContext", + "CloudRepoSourceContext", + "GerritSourceContext", + "GitSourceContext", + "RepoId", + "ProjectRepoId", + }, +) + + +class BuildProvenance(proto.Message): + r"""Provenance of a build. Contains all information needed to + verify the full details about the build from source to + completion. + + Attributes: + id (str): + Required. Unique identifier of the build. + project_id (str): + ID of the project. + commands (MutableSequence[grafeas.grafeas_v1.types.Command]): + Commands requested by the build. + built_artifacts (MutableSequence[grafeas.grafeas_v1.types.Artifact]): + Output of the build. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the build was created. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which execution of the build was + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which execution of the build was + finished. + creator (str): + E-mail address of the user who initiated this + build. Note that this was the user's e-mail + address at the time the build was initiated; + this address may not represent the same end-user + for all time. + logs_uri (str): + URI where any logs for this provenance were + written. + source_provenance (grafeas.grafeas_v1.types.Source): + Details of the Source input to the build. + trigger_id (str): + Trigger identifier if the build was triggered + automatically; empty if not. + build_options (MutableMapping[str, str]): + Special options applied to this build. This + is a catch-all field where build providers can + enter any desired additional details. + builder_version (str): + Version string of the builder at the time + this build was executed. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + commands: MutableSequence["Command"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Command", + ) + built_artifacts: MutableSequence["Artifact"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Artifact", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + creator: str = proto.Field( + proto.STRING, + number=8, + ) + logs_uri: str = proto.Field( + proto.STRING, + number=9, + ) + source_provenance: "Source" = proto.Field( + proto.MESSAGE, + number=10, + message="Source", + ) + trigger_id: str = proto.Field( + proto.STRING, + number=11, + ) + build_options: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + builder_version: str = proto.Field( + proto.STRING, + number=13, + ) + + +class Source(proto.Message): + r"""Source describes the location of the source used for the + build. + + Attributes: + artifact_storage_source_uri (str): + If provided, the input binary artifacts for + the build came from this location. + file_hashes (MutableMapping[str, grafeas.grafeas_v1.types.FileHashes]): + Hash(es) of the build source, which can be + used to verify that the original source + integrity was maintained in the build. + + The keys to this map are file paths used as + build source and the values contain the hash + values for those files. + + If the build source came in a single package + such as a gzipped tarfile (.tar.gz), the + FileHash will be for the single path to that + file. + context (grafeas.grafeas_v1.types.SourceContext): + If provided, the source code used for the + build came from this location. + additional_contexts (MutableSequence[grafeas.grafeas_v1.types.SourceContext]): + If provided, some of the source code used for + the build may be found in these locations, in + the case where the source repository had + multiple remotes or submodules. This list will + not include the context specified in the context + field. + """ + + artifact_storage_source_uri: str = proto.Field( + proto.STRING, + number=1, + ) + file_hashes: MutableMapping[str, "FileHashes"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="FileHashes", + ) + context: "SourceContext" = proto.Field( + proto.MESSAGE, + number=3, + message="SourceContext", + ) + additional_contexts: MutableSequence["SourceContext"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="SourceContext", + ) + + +class FileHashes(proto.Message): + r"""Container message for hashes of byte content of files, used + in source messages to verify integrity of source input to the + build. + + Attributes: + file_hash (MutableSequence[grafeas.grafeas_v1.types.Hash]): + Required. Collection of file hashes. + """ + + file_hash: MutableSequence["Hash"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Hash", + ) + + +class Hash(proto.Message): + r"""Container message for hash values. + + Attributes: + type_ (str): + Required. The type of hash that was + performed, e.g. "SHA-256". + value (bytes): + Required. The hash value. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + value: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class Command(proto.Message): + r"""Command describes a step performed as part of the build + pipeline. + + Attributes: + name (str): + Required. Name of the command, as presented on the command + line, or if the command is packaged as a Docker container, + as presented to ``docker pull``. + env (MutableSequence[str]): + Environment variables set before running this + command. + args (MutableSequence[str]): + Command-line arguments used when executing + this command. + dir_ (str): + Working directory (relative to project source + root) used when running this command. + id (str): + Optional unique identifier for this command, used in + wait_for to reference this command as a dependency. + wait_for (MutableSequence[str]): + The ID(s) of the command(s) that this command + depends on. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + env: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + dir_: str = proto.Field( + proto.STRING, + number=4, + ) + id: str = proto.Field( + proto.STRING, + number=5, + ) + wait_for: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class Artifact(proto.Message): + r"""Artifact describes a build product. + + Attributes: + checksum (str): + Hash or checksum value of a binary, or Docker + Registry 2.0 digest of a container. + id (str): + Artifact ID, if any; for container images, this will be a + URL by digest like + ``gcr.io/projectID/imagename@sha256:123456``. + names (MutableSequence[str]): + Related artifact names. This may be the path to a binary or + jar file, or in the case of a container build, the name used + to push the container image to Google Container Registry, as + presented to ``docker push``. Note that a single Artifact ID + can have multiple names, for example if two tags are applied + to one image. + """ + + checksum: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class SourceContext(proto.Message): + r"""A SourceContext is a reference to a tree of files. A + SourceContext together with a path point to a unique revision of + a single file or directory. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_repo (grafeas.grafeas_v1.types.CloudRepoSourceContext): + A SourceContext referring to a revision in a + Google Cloud Source Repo. + + This field is a member of `oneof`_ ``context``. + gerrit (grafeas.grafeas_v1.types.GerritSourceContext): + A SourceContext referring to a Gerrit + project. + + This field is a member of `oneof`_ ``context``. + git (grafeas.grafeas_v1.types.GitSourceContext): + A SourceContext referring to any third party + Git repo (e.g., GitHub). + + This field is a member of `oneof`_ ``context``. + labels (MutableMapping[str, str]): + Labels with user defined metadata. + """ + + cloud_repo: "CloudRepoSourceContext" = proto.Field( + proto.MESSAGE, + number=1, + oneof="context", + message="CloudRepoSourceContext", + ) + gerrit: "GerritSourceContext" = proto.Field( + proto.MESSAGE, + number=2, + oneof="context", + message="GerritSourceContext", + ) + git: "GitSourceContext" = proto.Field( + proto.MESSAGE, + number=3, + oneof="context", + message="GitSourceContext", + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class AliasContext(proto.Message): + r"""An alias to a repo revision. + + Attributes: + kind (grafeas.grafeas_v1.types.AliasContext.Kind): + The alias kind. + name (str): + The alias name. + """ + + class Kind(proto.Enum): + r"""The type of an alias. + + Values: + KIND_UNSPECIFIED (0): + Unknown. + FIXED (1): + Git tag. + MOVABLE (2): + Git branch. + OTHER (4): + Used to specify non-standard aliases. For + example, if a Git repo has a ref named + "refs/foo/bar". + """ + KIND_UNSPECIFIED = 0 + FIXED = 1 + MOVABLE = 2 + OTHER = 4 + + kind: Kind = proto.Field( + proto.ENUM, + number=1, + enum=Kind, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CloudRepoSourceContext(proto.Message): + r"""A CloudRepoSourceContext denotes a particular revision in a + Google Cloud Source Repo. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + repo_id (grafeas.grafeas_v1.types.RepoId): + The ID of the repo. + revision_id (str): + A revision ID. + + This field is a member of `oneof`_ ``revision``. + alias_context (grafeas.grafeas_v1.types.AliasContext): + An alias, which may be a branch or tag. + + This field is a member of `oneof`_ ``revision``. + """ + + repo_id: "RepoId" = proto.Field( + proto.MESSAGE, + number=1, + message="RepoId", + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + oneof="revision", + ) + alias_context: "AliasContext" = proto.Field( + proto.MESSAGE, + number=3, + oneof="revision", + message="AliasContext", + ) + + +class GerritSourceContext(proto.Message): + r"""A SourceContext referring to a Gerrit project. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + host_uri (str): + The URI of a running Gerrit instance. + gerrit_project (str): + The full project name within the host. + Projects may be nested, so "project/subproject" + is a valid project name. The "repo name" is the + hostURI/project. + revision_id (str): + A revision (commit) ID. + + This field is a member of `oneof`_ ``revision``. + alias_context (grafeas.grafeas_v1.types.AliasContext): + An alias, which may be a branch or tag. + + This field is a member of `oneof`_ ``revision``. + """ + + host_uri: str = proto.Field( + proto.STRING, + number=1, + ) + gerrit_project: str = proto.Field( + proto.STRING, + number=2, + ) + revision_id: str = proto.Field( + proto.STRING, + number=3, + oneof="revision", + ) + alias_context: "AliasContext" = proto.Field( + proto.MESSAGE, + number=4, + oneof="revision", + message="AliasContext", + ) + + +class GitSourceContext(proto.Message): + r"""A GitSourceContext denotes a particular revision in a third + party Git repository (e.g., GitHub). + + Attributes: + url (str): + Git repository URL. + revision_id (str): + Git commit hash. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RepoId(proto.Message): + r"""A unique identifier for a Cloud Repo. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project_repo_id (grafeas.grafeas_v1.types.ProjectRepoId): + A combination of a project ID and a repo + name. + + This field is a member of `oneof`_ ``id``. + uid (str): + A server-assigned, globally unique + identifier. + + This field is a member of `oneof`_ ``id``. + """ + + project_repo_id: "ProjectRepoId" = proto.Field( + proto.MESSAGE, + number=1, + oneof="id", + message="ProjectRepoId", + ) + uid: str = proto.Field( + proto.STRING, + number=2, + oneof="id", + ) + + +class ProjectRepoId(proto.Message): + r"""Selects a repo using a Google Cloud Platform project ID + (e.g., winged-cargo-31) and a repo name within that project. + + Attributes: + project_id (str): + The ID of the project. + repo_name (str): + The name of the repo. Leave empty for the + default repo. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + repo_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/sbom.py b/packages/grafeas/grafeas/grafeas_v1/types/sbom.py new file mode 100644 index 000000000000..79bcc14daf6a --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/sbom.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import common, intoto_statement + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "SBOMReferenceNote", + "SBOMReferenceOccurrence", + "SbomReferenceIntotoPayload", + "SbomReferenceIntotoPredicate", + }, +) + + +class SBOMReferenceNote(proto.Message): + r"""The note representing an SBOM reference. + + Attributes: + format_ (str): + The format that SBOM takes. E.g. may be spdx, + cyclonedx, etc... + version (str): + The version of the format that the SBOM + takes. E.g. if the format is spdx, the version + may be 2.3. + """ + + format_: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SBOMReferenceOccurrence(proto.Message): + r"""The occurrence representing an SBOM reference as applied to a + specific resource. The occurrence follows the DSSE + specification. See + https://github.com/secure-systems-lab/dsse/blob/master/envelope.md + for more details. + + Attributes: + payload (grafeas.grafeas_v1.types.SbomReferenceIntotoPayload): + The actual payload that contains the SBOM + reference data. + payload_type (str): + The kind of payload that + SbomReferenceIntotoPayload takes. Since it's in + the intoto format, this value is expected to be + 'application/vnd.in-toto+json'. + signatures (MutableSequence[grafeas.grafeas_v1.types.EnvelopeSignature]): + The signatures over the payload. + """ + + payload: "SbomReferenceIntotoPayload" = proto.Field( + proto.MESSAGE, + number=1, + message="SbomReferenceIntotoPayload", + ) + payload_type: str = proto.Field( + proto.STRING, + number=2, + ) + signatures: MutableSequence[common.EnvelopeSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=common.EnvelopeSignature, + ) + + +class SbomReferenceIntotoPayload(proto.Message): + r"""The actual payload that contains the SBOM Reference data. + The payload follows the intoto statement specification. See + https://github.com/in-toto/attestation/blob/main/spec/v1.0/statement.md + for more details. + + Attributes: + type_ (str): + Identifier for the schema of the Statement. + predicate_type (str): + URI identifying the type of the Predicate. + subject (MutableSequence[grafeas.grafeas_v1.types.Subject]): + Set of software artifacts that the + attestation applies to. Each element represents + a single software artifact. + predicate (grafeas.grafeas_v1.types.SbomReferenceIntotoPredicate): + Additional parameters of the Predicate. + Includes the actual data about the SBOM. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + predicate_type: str = proto.Field( + proto.STRING, + number=2, + ) + subject: MutableSequence[intoto_statement.Subject] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=intoto_statement.Subject, + ) + predicate: "SbomReferenceIntotoPredicate" = proto.Field( + proto.MESSAGE, + number=4, + message="SbomReferenceIntotoPredicate", + ) + + +class SbomReferenceIntotoPredicate(proto.Message): + r"""A predicate which describes the SBOM being referenced. + + Attributes: + referrer_id (str): + The person or system referring this predicate + to the consumer. + location (str): + The location of the SBOM. + mime_type (str): + The mime type of the SBOM. + digest (MutableMapping[str, str]): + A map of algorithm to digest of the contents + of the SBOM. + """ + + referrer_id: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/secret.py b/packages/grafeas/grafeas/grafeas_v1/types/secret.py new file mode 100644 index 000000000000..e36597dd1430 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/secret.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import common + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "SecretKind", + "SecretNote", + "SecretOccurrence", + "SecretLocation", + "SecretStatus", + }, +) + + +class SecretKind(proto.Enum): + r"""Kind of secret. + + Values: + SECRET_KIND_UNSPECIFIED (0): + Unspecified + SECRET_KIND_UNKNOWN (1): + The secret kind is unknown. + SECRET_KIND_GCP_SERVICE_ACCOUNT_KEY (2): + A GCP service account key per: + + https://cloud.google.com/iam/docs/creating-managing-service-account-keys + """ + SECRET_KIND_UNSPECIFIED = 0 + SECRET_KIND_UNKNOWN = 1 + SECRET_KIND_GCP_SERVICE_ACCOUNT_KEY = 2 + + +class SecretNote(proto.Message): + r"""The note representing a secret.""" + + +class SecretOccurrence(proto.Message): + r"""The occurrence provides details of a secret. + + Attributes: + kind (grafeas.grafeas_v1.types.SecretKind): + Type of secret. + locations (MutableSequence[grafeas.grafeas_v1.types.SecretLocation]): + Locations where the secret is detected. + statuses (MutableSequence[grafeas.grafeas_v1.types.SecretStatus]): + Status of the secret. + """ + + kind: "SecretKind" = proto.Field( + proto.ENUM, + number=1, + enum="SecretKind", + ) + locations: MutableSequence["SecretLocation"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SecretLocation", + ) + statuses: MutableSequence["SecretStatus"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SecretStatus", + ) + + +class SecretLocation(proto.Message): + r"""The location of the secret. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + file_location (grafeas.grafeas_v1.types.FileLocation): + The secret is found from a file. + + This field is a member of `oneof`_ ``location``. + """ + + file_location: common.FileLocation = proto.Field( + proto.MESSAGE, + number=1, + oneof="location", + message=common.FileLocation, + ) + + +class SecretStatus(proto.Message): + r"""The status of the secret with a timestamp. + + Attributes: + status (grafeas.grafeas_v1.types.SecretStatus.Status): + The status of the secret. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time the secret status was last updated. + message (str): + Optional message about the status code. + """ + + class Status(proto.Enum): + r"""The status of the secret. + + Values: + STATUS_UNSPECIFIED (0): + Unspecified + UNKNOWN (1): + The status of the secret is unknown. + VALID (2): + The secret is valid. + INVALID (3): + The secret is invalid. + """ + STATUS_UNSPECIFIED = 0 + UNKNOWN = 1 + VALID = 2 + INVALID = 3 + + status: Status = proto.Field( + proto.ENUM, + number=1, + enum=Status, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + message: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/severity.py b/packages/grafeas/grafeas/grafeas_v1/types/severity.py new file mode 100644 index 000000000000..af2b165d5678 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/severity.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "Severity", + }, +) + + +class Severity(proto.Enum): + r"""Note provider assigned severity/impact ranking. + + Values: + SEVERITY_UNSPECIFIED (0): + Unknown. + MINIMAL (1): + Minimal severity. + LOW (2): + Low severity. + MEDIUM (3): + Medium severity. + HIGH (4): + High severity. + CRITICAL (5): + Critical severity. + """ + SEVERITY_UNSPECIFIED = 0 + MINIMAL = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + CRITICAL = 5 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py b/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py new file mode 100644 index 000000000000..0640bae93566 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "SlsaProvenance", + }, +) + + +class SlsaProvenance(proto.Message): + r""" + + Attributes: + builder (grafeas.grafeas_v1.types.SlsaProvenance.SlsaBuilder): + required + recipe (grafeas.grafeas_v1.types.SlsaProvenance.SlsaRecipe): + Identifies the configuration used for the + build. When combined with materials, this SHOULD + fully describe the build, such that re-running + this recipe results in bit-for-bit identical + output (if the build is reproducible). + metadata (grafeas.grafeas_v1.types.SlsaProvenance.SlsaMetadata): + + materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenance.Material]): + The collection of artifacts that influenced + the build including sources, dependencies, build + tools, base images, and so on. This is + considered to be incomplete unless + metadata.completeness.materials is true. Unset + or null is equivalent to empty. + """ + + class SlsaRecipe(proto.Message): + r"""Steps taken to build the artifact. + For a TaskRun, typically each container corresponds to one step + in the recipe. + + Attributes: + type_ (str): + URI indicating what type of recipe was + performed. It determines the meaning of + recipe.entryPoint, recipe.arguments, + recipe.environment, and materials. + defined_in_material (int): + Index in materials containing the recipe + steps that are not implied by recipe.type. For + example, if the recipe type were "make", then + this would point to the source containing the + Makefile, not the make program itself. Set to -1 + if the recipe doesn't come from a material, as + zero is default unset value for int64. + entry_point (str): + String identifying the entry point into the + build. This is often a path to a configuration + file and/or a target label within that file. The + syntax and meaning are defined by recipe.type. + For example, if the recipe type were "make", + then this would reference the directory in which + to run make as well as which target to use. + arguments (google.protobuf.any_pb2.Any): + Collection of all external inputs that + influenced the build on top of + recipe.definedInMaterial and recipe.entryPoint. + For example, if the recipe type were "make", + then this might be the flags passed to make + aside from the target, which is captured in + recipe.entryPoint. Depending on the recipe Type, + the structure may be different. + environment (google.protobuf.any_pb2.Any): + Any other builder-controlled inputs necessary + for correctly evaluating the recipe. Usually + only needed for reproducing the build but not + evaluated as part of policy. Depending on the + recipe Type, the structure may be different. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + defined_in_material: int = proto.Field( + proto.INT64, + number=2, + ) + entry_point: str = proto.Field( + proto.STRING, + number=3, + ) + arguments: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=4, + message=any_pb2.Any, + ) + environment: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=5, + message=any_pb2.Any, + ) + + class SlsaCompleteness(proto.Message): + r"""Indicates that the builder claims certain fields in this + message to be complete. + + Attributes: + arguments (bool): + If true, the builder claims that + recipe.arguments is complete, meaning that all + external inputs are properly captured in the + recipe. + environment (bool): + If true, the builder claims that + recipe.environment is claimed to be complete. + materials (bool): + If true, the builder claims that materials + are complete, usually through some controls to + prevent network access. Sometimes called + "hermetic". + """ + + arguments: bool = proto.Field( + proto.BOOL, + number=1, + ) + environment: bool = proto.Field( + proto.BOOL, + number=2, + ) + materials: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SlsaMetadata(proto.Message): + r"""Other properties of the build. + + Attributes: + build_invocation_id (str): + Identifies the particular build invocation, + which can be useful for finding associated logs + or other ad-hoc analysis. The value SHOULD be + globally unique, per in-toto Provenance spec. + build_started_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build started. + build_finished_on (google.protobuf.timestamp_pb2.Timestamp): + The timestamp of when the build completed. + completeness (grafeas.grafeas_v1.types.SlsaProvenance.SlsaCompleteness): + Indicates that the builder claims certain + fields in this message to be complete. + reproducible (bool): + If true, the builder claims that running the + recipe on materials will produce bit-for-bit + identical output. + """ + + build_invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + build_started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + build_finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completeness: "SlsaProvenance.SlsaCompleteness" = proto.Field( + proto.MESSAGE, + number=4, + message="SlsaProvenance.SlsaCompleteness", + ) + reproducible: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class SlsaBuilder(proto.Message): + r""" + + Attributes: + id (str): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class Material(proto.Message): + r""" + + Attributes: + uri (str): + + digest (MutableMapping[str, str]): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + builder: SlsaBuilder = proto.Field( + proto.MESSAGE, + number=1, + message=SlsaBuilder, + ) + recipe: SlsaRecipe = proto.Field( + proto.MESSAGE, + number=2, + message=SlsaRecipe, + ) + metadata: SlsaMetadata = proto.Field( + proto.MESSAGE, + number=3, + message=SlsaMetadata, + ) + materials: MutableSequence[Material] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Material, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py b/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py new file mode 100644 index 000000000000..590263762adf --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/slsa_provenance_zero_two.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "SlsaProvenanceZeroTwo", + }, +) + + +class SlsaProvenanceZeroTwo(proto.Message): + r"""See full explanation of fields at slsa.dev/provenance/v0.2. + + Attributes: + builder (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaBuilder): + + build_type (str): + + invocation (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaInvocation): + + build_config (google.protobuf.struct_pb2.Struct): + + metadata (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMetadata): + + materials (MutableSequence[grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaMaterial]): + + """ + + class SlsaBuilder(proto.Message): + r"""Identifies the entity that executed the recipe, which is + trusted to have correctly performed the operation and populated + this provenance. + + Attributes: + id (str): + + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class SlsaMaterial(proto.Message): + r"""The collection of artifacts that influenced the build + including sources, dependencies, build tools, base images, and + so on. + + Attributes: + uri (str): + + digest (MutableMapping[str, str]): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + class SlsaInvocation(proto.Message): + r"""Identifies the event that kicked off the build. + + Attributes: + config_source (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaConfigSource): + + parameters (google.protobuf.struct_pb2.Struct): + + environment (google.protobuf.struct_pb2.Struct): + + """ + + config_source: "SlsaProvenanceZeroTwo.SlsaConfigSource" = proto.Field( + proto.MESSAGE, + number=1, + message="SlsaProvenanceZeroTwo.SlsaConfigSource", + ) + parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + environment: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + class SlsaConfigSource(proto.Message): + r"""Describes where the config file that kicked off the build + came from. This is effectively a pointer to the source where + buildConfig came from. + + Attributes: + uri (str): + + digest (MutableMapping[str, str]): + + entry_point (str): + + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + digest: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + entry_point: str = proto.Field( + proto.STRING, + number=3, + ) + + class SlsaMetadata(proto.Message): + r"""Other properties of the build. + + Attributes: + build_invocation_id (str): + + build_started_on (google.protobuf.timestamp_pb2.Timestamp): + + build_finished_on (google.protobuf.timestamp_pb2.Timestamp): + + completeness (grafeas.grafeas_v1.types.SlsaProvenanceZeroTwo.SlsaCompleteness): + + reproducible (bool): + + """ + + build_invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + build_started_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + build_finished_on: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completeness: "SlsaProvenanceZeroTwo.SlsaCompleteness" = proto.Field( + proto.MESSAGE, + number=4, + message="SlsaProvenanceZeroTwo.SlsaCompleteness", + ) + reproducible: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class SlsaCompleteness(proto.Message): + r"""Indicates that the builder claims certain fields in this + message to be complete. + + Attributes: + parameters (bool): + + environment (bool): + + materials (bool): + + """ + + parameters: bool = proto.Field( + proto.BOOL, + number=1, + ) + environment: bool = proto.Field( + proto.BOOL, + number=2, + ) + materials: bool = proto.Field( + proto.BOOL, + number=3, + ) + + builder: SlsaBuilder = proto.Field( + proto.MESSAGE, + number=1, + message=SlsaBuilder, + ) + build_type: str = proto.Field( + proto.STRING, + number=2, + ) + invocation: SlsaInvocation = proto.Field( + proto.MESSAGE, + number=3, + message=SlsaInvocation, + ) + build_config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + metadata: SlsaMetadata = proto.Field( + proto.MESSAGE, + number=5, + message=SlsaMetadata, + ) + materials: MutableSequence[SlsaMaterial] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=SlsaMaterial, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/upgrade.py b/packages/grafeas/grafeas/grafeas_v1/types/upgrade.py new file mode 100644 index 000000000000..9621aa1f85d7 --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/upgrade.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import package as g_package + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "UpgradeNote", + "UpgradeDistribution", + "WindowsUpdate", + "UpgradeOccurrence", + }, +) + + +class UpgradeNote(proto.Message): + r"""An Upgrade Note represents a potential upgrade of a package to a + given version. For each package version combination (i.e. bash 4.0, + bash 4.1, bash 4.1.2), there will be an Upgrade Note. For Windows, + windows_update field represents the information related to the + update. + + Attributes: + package (str): + Required for non-Windows OS. The package this + Upgrade is for. + version (grafeas.grafeas_v1.types.Version): + Required for non-Windows OS. The version of + the package in machine + human readable form. + distributions (MutableSequence[grafeas.grafeas_v1.types.UpgradeDistribution]): + Metadata about the upgrade for each specific + operating system. + windows_update (grafeas.grafeas_v1.types.WindowsUpdate): + Required for Windows OS. Represents the + metadata about the Windows update. + """ + + package: str = proto.Field( + proto.STRING, + number=1, + ) + version: g_package.Version = proto.Field( + proto.MESSAGE, + number=2, + message=g_package.Version, + ) + distributions: MutableSequence["UpgradeDistribution"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="UpgradeDistribution", + ) + windows_update: "WindowsUpdate" = proto.Field( + proto.MESSAGE, + number=4, + message="WindowsUpdate", + ) + + +class UpgradeDistribution(proto.Message): + r"""The Upgrade Distribution represents metadata about the + Upgrade for each operating system (CPE). Some distributions have + additional metadata around updates, classifying them into + various categories and severities. + + Attributes: + cpe_uri (str): + Required - The specific operating system this + metadata applies to. See + https://cpe.mitre.org/specification/. + classification (str): + The operating system classification of this Upgrade, as + specified by the upstream operating system upgrade feed. For + Windows the classification is one of the category_ids listed + at + https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ff357803(v=vs.85) + severity (str): + The severity as specified by the upstream + operating system. + cve (MutableSequence[str]): + The cve tied to this Upgrade. + """ + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + classification: str = proto.Field( + proto.STRING, + number=2, + ) + severity: str = proto.Field( + proto.STRING, + number=3, + ) + cve: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class WindowsUpdate(proto.Message): + r"""Windows Update represents the metadata about the update for + the Windows operating system. The fields in this message come + from the Windows Update API documented at + https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nn-wuapi-iupdate. + + Attributes: + identity (grafeas.grafeas_v1.types.WindowsUpdate.Identity): + Required - The unique identifier for the + update. + title (str): + The localized title of the update. + description (str): + The localized description of the update. + categories (MutableSequence[grafeas.grafeas_v1.types.WindowsUpdate.Category]): + The list of categories to which the update + belongs. + kb_article_ids (MutableSequence[str]): + The Microsoft Knowledge Base article IDs that + are associated with the update. + support_url (str): + The hyperlink to the support information for + the update. + last_published_timestamp (google.protobuf.timestamp_pb2.Timestamp): + The last published timestamp of the update. + """ + + class Identity(proto.Message): + r"""The unique identifier of the update. + + Attributes: + update_id (str): + The revision independent identifier of the + update. + revision (int): + The revision number of the update. + """ + + update_id: str = proto.Field( + proto.STRING, + number=1, + ) + revision: int = proto.Field( + proto.INT32, + number=2, + ) + + class Category(proto.Message): + r"""The category to which the update belongs. + + Attributes: + category_id (str): + The identifier of the category. + name (str): + The localized name of the category. + """ + + category_id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + identity: Identity = proto.Field( + proto.MESSAGE, + number=1, + message=Identity, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + categories: MutableSequence[Category] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Category, + ) + kb_article_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + support_url: str = proto.Field( + proto.STRING, + number=6, + ) + last_published_timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +class UpgradeOccurrence(proto.Message): + r"""An Upgrade Occurrence represents that a specific resource_url could + install a specific upgrade. This presence is supplied via local + sources (i.e. it is present in the mirror and the running system has + noticed its availability). For Windows, both distribution and + windows_update contain information for the Windows update. + + Attributes: + package (str): + Required for non-Windows OS. The package this + Upgrade is for. + parsed_version (grafeas.grafeas_v1.types.Version): + Required for non-Windows OS. The version of + the package in a machine + human readable form. + distribution (grafeas.grafeas_v1.types.UpgradeDistribution): + Metadata about the upgrade for available for the specific + operating system for the resource_url. This allows efficient + filtering, as well as making it easier to use the + occurrence. + windows_update (grafeas.grafeas_v1.types.WindowsUpdate): + Required for Windows OS. Represents the + metadata about the Windows update. + """ + + package: str = proto.Field( + proto.STRING, + number=1, + ) + parsed_version: g_package.Version = proto.Field( + proto.MESSAGE, + number=3, + message=g_package.Version, + ) + distribution: "UpgradeDistribution" = proto.Field( + proto.MESSAGE, + number=4, + message="UpgradeDistribution", + ) + windows_update: "WindowsUpdate" = proto.Field( + proto.MESSAGE, + number=5, + message="WindowsUpdate", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/vex.py b/packages/grafeas/grafeas/grafeas_v1/types/vex.py new file mode 100644 index 000000000000..a0a0666736ee --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/vex.py @@ -0,0 +1,390 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from grafeas.grafeas_v1.types import common + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "VulnerabilityAssessmentNote", + }, +) + + +class VulnerabilityAssessmentNote(proto.Message): + r"""A single VulnerabilityAssessmentNote represents + one particular product's vulnerability assessment for one CVE. + + Attributes: + title (str): + The title of the note. E.g. ``Vex-Debian-11.4`` + short_description (str): + A one sentence description of this Vex. + long_description (str): + A detailed description of this Vex. + language_code (str): + Identifies the language used by this + document, corresponding to IETF BCP 47 / RFC + 5646. + publisher (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Publisher): + Publisher details of this Note. + product (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Product): + The product affected by this vex. + assessment (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment): + Represents a vulnerability assessment for the + product. + """ + + class Publisher(proto.Message): + r"""Publisher contains information about the publisher of + this Note. + (-- api-linter: core::0123::resource-annotation=disabled + aip.dev/not-precedent: Publisher is not a separate resource. --) + + Attributes: + name (str): + Name of the publisher. + Examples: 'Google', 'Google Cloud Platform'. + issuing_authority (str): + Provides information about the authority of + the issuing party to release the document, in + particular, the party's constituency and + responsibilities or other obligations. + publisher_namespace (str): + The context or namespace. + Contains a URL which is under control of the + issuing party and can be used as a globally + unique identifier for that issuing party. + Example: https://csaf.io + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + issuing_authority: str = proto.Field( + proto.STRING, + number=2, + ) + publisher_namespace: str = proto.Field( + proto.STRING, + number=3, + ) + + class Product(proto.Message): + r"""Product contains information about a product and how to + uniquely identify it. + (-- api-linter: core::0123::resource-annotation=disabled + aip.dev/not-precedent: Product is not a separate resource. --) + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the product. + id (str): + Token that identifies a product so that it + can be referred to from other parts in the + document. There is no predefined format as long + as it uniquely identifies a group in the context + of the current document. + generic_uri (str): + Contains a URI which is vendor-specific. + Example: The artifact repository URL of an + image. + + This field is a member of `oneof`_ ``identifier``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + generic_uri: str = proto.Field( + proto.STRING, + number=3, + oneof="identifier", + ) + + class Assessment(proto.Message): + r"""Assessment provides all information that is related to a + single vulnerability for this product. + + Attributes: + cve (str): + Holds the MITRE standard Common Vulnerabilities and + Exposures (CVE) tracking number for the vulnerability. + Deprecated: Use vulnerability_id instead to denote CVEs. + vulnerability_id (str): + The vulnerability identifier for this + Assessment. Will hold one of common identifiers + e.g. CVE, GHSA etc. + short_description (str): + A one sentence description of this Vex. + long_description (str): + A detailed description of this Vex. + related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + Holds a list of references associated with + this vulnerability item and assessment. These + uris have additional information about the + vulnerability and the assessment itself. E.g. + Link to a document which details how this + assessment concluded the state of this + vulnerability. + state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): + Provides the state of this Vulnerability + assessment. + impacts (MutableSequence[str]): + Contains information about the impact of this + vulnerability, this will change with time. + justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): + Justification provides the justification when the state of + the assessment if NOT_AFFECTED. + remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): + Specifies details on how to handle (and + presumably, fix) a vulnerability. + """ + + class State(proto.Enum): + r"""Provides the state of this Vulnerability assessment. + + Values: + STATE_UNSPECIFIED (0): + No state is specified. + AFFECTED (1): + This product is known to be affected by this + vulnerability. + NOT_AFFECTED (2): + This product is known to be not affected by + this vulnerability. + FIXED (3): + This product contains a fix for this + vulnerability. + UNDER_INVESTIGATION (4): + It is not known yet whether these versions + are or are not affected by the vulnerability. + However, it is still under investigation. + """ + STATE_UNSPECIFIED = 0 + AFFECTED = 1 + NOT_AFFECTED = 2 + FIXED = 3 + UNDER_INVESTIGATION = 4 + + class Justification(proto.Message): + r"""Justification provides the justification when the state of the + assessment if NOT_AFFECTED. + + Attributes: + justification_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification.JustificationType): + The justification type for this + vulnerability. + details (str): + Additional details on why this justification + was chosen. + """ + + class JustificationType(proto.Enum): + r"""Provides the type of justification. + + Values: + JUSTIFICATION_TYPE_UNSPECIFIED (0): + JUSTIFICATION_TYPE_UNSPECIFIED. + COMPONENT_NOT_PRESENT (1): + The vulnerable component is not present in + the product. + VULNERABLE_CODE_NOT_PRESENT (2): + The vulnerable code is not present. Typically + this case occurs when source code is configured + or built in a way that excludes the vulnerable + code. + VULNERABLE_CODE_NOT_IN_EXECUTE_PATH (3): + The vulnerable code can not be executed. + Typically this case occurs when the product + includes the vulnerable code but does not call + or use the vulnerable code. + VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY (4): + The vulnerable code cannot be controlled by + an attacker to exploit the vulnerability. + INLINE_MITIGATIONS_ALREADY_EXIST (5): + The product includes built-in protections or + features that prevent exploitation of the + vulnerability. These built-in protections cannot + be subverted by the attacker and cannot be + configured or disabled by the user. These + mitigations completely prevent exploitation + based on known attack vectors. + """ + JUSTIFICATION_TYPE_UNSPECIFIED = 0 + COMPONENT_NOT_PRESENT = 1 + VULNERABLE_CODE_NOT_PRESENT = 2 + VULNERABLE_CODE_NOT_IN_EXECUTE_PATH = 3 + VULNERABLE_CODE_CANNOT_BE_CONTROLLED_BY_ADVERSARY = 4 + INLINE_MITIGATIONS_ALREADY_EXIST = 5 + + justification_type: "VulnerabilityAssessmentNote.Assessment.Justification.JustificationType" = proto.Field( + proto.ENUM, + number=1, + enum="VulnerabilityAssessmentNote.Assessment.Justification.JustificationType", + ) + details: str = proto.Field( + proto.STRING, + number=2, + ) + + class Remediation(proto.Message): + r"""Specifies details on how to handle (and presumably, fix) a + vulnerability. + + Attributes: + remediation_type (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType): + The type of remediation that can be applied. + details (str): + Contains a comprehensive human-readable + discussion of the remediation. + remediation_uri (grafeas.grafeas_v1.types.RelatedUrl): + Contains the URL where to obtain the + remediation. + """ + + class RemediationType(proto.Enum): + r"""The type of remediation that can be applied. + + Values: + REMEDIATION_TYPE_UNSPECIFIED (0): + No remediation type specified. + MITIGATION (1): + A MITIGATION is available. + NO_FIX_PLANNED (2): + No fix is planned. + NONE_AVAILABLE (3): + Not available. + VENDOR_FIX (4): + A vendor fix is available. + WORKAROUND (5): + A workaround is available. + """ + REMEDIATION_TYPE_UNSPECIFIED = 0 + MITIGATION = 1 + NO_FIX_PLANNED = 2 + NONE_AVAILABLE = 3 + VENDOR_FIX = 4 + WORKAROUND = 5 + + remediation_type: "VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType" = proto.Field( + proto.ENUM, + number=1, + enum="VulnerabilityAssessmentNote.Assessment.Remediation.RemediationType", + ) + details: str = proto.Field( + proto.STRING, + number=2, + ) + remediation_uri: common.RelatedUrl = proto.Field( + proto.MESSAGE, + number=3, + message=common.RelatedUrl, + ) + + cve: str = proto.Field( + proto.STRING, + number=1, + ) + vulnerability_id: str = proto.Field( + proto.STRING, + number=9, + ) + short_description: str = proto.Field( + proto.STRING, + number=2, + ) + long_description: str = proto.Field( + proto.STRING, + number=3, + ) + related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=common.RelatedUrl, + ) + state: "VulnerabilityAssessmentNote.Assessment.State" = proto.Field( + proto.ENUM, + number=5, + enum="VulnerabilityAssessmentNote.Assessment.State", + ) + impacts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + justification: "VulnerabilityAssessmentNote.Assessment.Justification" = ( + proto.Field( + proto.MESSAGE, + number=7, + message="VulnerabilityAssessmentNote.Assessment.Justification", + ) + ) + remediations: MutableSequence[ + "VulnerabilityAssessmentNote.Assessment.Remediation" + ] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="VulnerabilityAssessmentNote.Assessment.Remediation", + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + short_description: str = proto.Field( + proto.STRING, + number=2, + ) + long_description: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + publisher: Publisher = proto.Field( + proto.MESSAGE, + number=5, + message=Publisher, + ) + product: Product = proto.Field( + proto.MESSAGE, + number=6, + message=Product, + ) + assessment: Assessment = proto.Field( + proto.MESSAGE, + number=7, + message=Assessment, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py b/packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py new file mode 100644 index 000000000000..42da348e7a7d --- /dev/null +++ b/packages/grafeas/grafeas/grafeas_v1/types/vulnerability.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from grafeas.grafeas_v1.types import common, cvss, package +from grafeas.grafeas_v1.types import severity as g_severity +from grafeas.grafeas_v1.types import vex + +__protobuf__ = proto.module( + package="grafeas.v1", + manifest={ + "VulnerabilityNote", + "VulnerabilityOccurrence", + }, +) + + +class VulnerabilityNote(proto.Message): + r"""A security vulnerability that can be found in resources. + + Attributes: + cvss_score (float): + The CVSS score of this vulnerability. CVSS + score is on a scale of 0 - 10 where 0 indicates + low severity and 10 indicates high severity. + severity (grafeas.grafeas_v1.types.Severity): + The note provider assigned severity of this + vulnerability. + details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.Detail]): + Details of all known distros and packages + affected by this vulnerability. + cvss_v3 (grafeas.grafeas_v1.types.CVSSv3): + The full description of the CVSSv3 for this + vulnerability. + windows_details (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail]): + Windows details get their own format because + the information format and model don't match a + normal detail. Specifically Windows updates are + done as patches, thus Windows vulnerabilities + really are a missing package, rather than a + package being at an incorrect version. + source_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this information was last changed at + the source. This is an upstream timestamp from + the underlying information source - e.g. Ubuntu + security tracker. + cvss_version (grafeas.grafeas_v1.types.CVSSVersion): + CVSS version used to populate cvss_score and severity. + cvss_v2 (grafeas.grafeas_v1.types.CVSS): + The full description of the v2 CVSS for this + vulnerability. + """ + + class Detail(proto.Message): + r"""A detail for a distro and package affected by this + vulnerability and its associated fix (if one is available). + + Attributes: + severity_name (str): + The distro assigned severity of this + vulnerability. + description (str): + A vendor-specific description of this + vulnerability. + package_type (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + affected_cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability affects. + affected_package (str): + Required. The package this vulnerability + affects. + affected_version_start (grafeas.grafeas_v1.types.Version): + The version number at the start of an interval in which this + vulnerability exists. A vulnerability can affect a package + between version numbers that are disjoint sets of intervals + (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) + each of which will be represented in its own Detail. If a + specific affected version is provided by a vulnerability + database, affected_version_start and affected_version_end + will be the same in that Detail. + affected_version_end (grafeas.grafeas_v1.types.Version): + The version number at the end of an interval in which this + vulnerability exists. A vulnerability can affect a package + between version numbers that are disjoint sets of intervals + (example: [1.0.0-1.1.0], [2.4.6-2.4.8] and [4.5.6-4.6.8]) + each of which will be represented in its own Detail. If a + specific affected version is provided by a vulnerability + database, affected_version_start and affected_version_end + will be the same in that Detail. + fixed_cpe_uri (str): + The distro recommended `CPE + URI `__ to update to + that contains a fix for this vulnerability. It is possible + for this to be different from the affected_cpe_uri. + fixed_package (str): + The distro recommended package to update to that contains a + fix for this vulnerability. It is possible for this to be + different from the affected_package. + fixed_version (grafeas.grafeas_v1.types.Version): + The distro recommended version to update to + that contains a fix for this vulnerability. + Setting this to VersionKind.MAXIMUM means no + such version is yet available. + is_obsolete (bool): + Whether this detail is obsolete. Occurrences + are expected not to point to obsolete details. + source_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this information was last changed at + the source. This is an upstream timestamp from + the underlying information source - e.g. Ubuntu + security tracker. + source (str): + The source from which the information in this + Detail was obtained. + vendor (str): + The name of the vendor of the product. + """ + + severity_name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + affected_cpe_uri: str = proto.Field( + proto.STRING, + number=4, + ) + affected_package: str = proto.Field( + proto.STRING, + number=5, + ) + affected_version_start: package.Version = proto.Field( + proto.MESSAGE, + number=6, + message=package.Version, + ) + affected_version_end: package.Version = proto.Field( + proto.MESSAGE, + number=7, + message=package.Version, + ) + fixed_cpe_uri: str = proto.Field( + proto.STRING, + number=8, + ) + fixed_package: str = proto.Field( + proto.STRING, + number=9, + ) + fixed_version: package.Version = proto.Field( + proto.MESSAGE, + number=10, + message=package.Version, + ) + is_obsolete: bool = proto.Field( + proto.BOOL, + number=11, + ) + source_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + source: str = proto.Field( + proto.STRING, + number=13, + ) + vendor: str = proto.Field( + proto.STRING, + number=14, + ) + + class WindowsDetail(proto.Message): + r""" + + Attributes: + cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability affects. + name (str): + Required. The name of this vulnerability. + description (str): + The description of this vulnerability. + fixing_kbs (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityNote.WindowsDetail.KnowledgeBase]): + Required. The names of the KBs which have + hotfixes to mitigate this vulnerability. Note + that there may be multiple hotfixes (and thus + multiple KBs) that mitigate a given + vulnerability. Currently any listed KBs presence + is considered a fix. + """ + + class KnowledgeBase(proto.Message): + r""" + + Attributes: + name (str): + The KB name (generally of the form KB[0-9]+ (e.g., + KB123456)). + url (str): + A link to the KB in the [Windows update catalog] + (https://www.catalog.update.microsoft.com/). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + + cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + fixing_kbs: MutableSequence[ + "VulnerabilityNote.WindowsDetail.KnowledgeBase" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="VulnerabilityNote.WindowsDetail.KnowledgeBase", + ) + + cvss_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=2, + enum=g_severity.Severity, + ) + details: MutableSequence[Detail] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Detail, + ) + cvss_v3: cvss.CVSSv3 = proto.Field( + proto.MESSAGE, + number=4, + message=cvss.CVSSv3, + ) + windows_details: MutableSequence[WindowsDetail] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=WindowsDetail, + ) + source_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + cvss_version: cvss.CVSSVersion = proto.Field( + proto.ENUM, + number=7, + enum=cvss.CVSSVersion, + ) + cvss_v2: cvss.CVSS = proto.Field( + proto.MESSAGE, + number=8, + message=cvss.CVSS, + ) + + +class VulnerabilityOccurrence(proto.Message): + r"""An occurrence of a severity vulnerability on a resource. + + Attributes: + type_ (str): + The type of package; whether native or non + native (e.g., ruby gems, node.js packages, + etc.). + severity (grafeas.grafeas_v1.types.Severity): + Output only. The note provider assigned + severity of this vulnerability. + cvss_score (float): + Output only. The CVSS score of this + vulnerability. CVSS score is on a scale of 0 - + 10 where 0 indicates low severity and 10 + indicates high severity. + cvssv3 (grafeas.grafeas_v1.types.CVSS): + The cvss v3 score for the vulnerability. + package_issue (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityOccurrence.PackageIssue]): + Required. The set of affected locations and + their fixes (if available) within the associated + resource. + short_description (str): + Output only. A one sentence description of + this vulnerability. + long_description (str): + Output only. A detailed description of this + vulnerability. + related_urls (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + Output only. URLs related to this + vulnerability. + effective_severity (grafeas.grafeas_v1.types.Severity): + The distro assigned severity for this + vulnerability when it is available, otherwise + this is the note provider assigned severity. + + When there are multiple PackageIssues for this + vulnerability, they can have different effective + severities because some might be provided by the + distro while others are provided by the language + ecosystem for a language pack. For this reason, + it is advised to use the effective severity on + the PackageIssue level. In the case where + multiple PackageIssues have differing effective + severities, this field should be the highest + severity for any of the PackageIssues. + fix_available (bool): + Output only. Whether at least one of the + affected packages has a fix available. + cvss_version (grafeas.grafeas_v1.types.CVSSVersion): + Output only. CVSS version used to populate cvss_score and + severity. + cvss_v2 (grafeas.grafeas_v1.types.CVSS): + The cvss v2 score for the vulnerability. + vex_assessment (grafeas.grafeas_v1.types.VulnerabilityOccurrence.VexAssessment): + + extra_details (str): + Occurrence-specific extra details about the + vulnerability. + """ + + class PackageIssue(proto.Message): + r"""A detail for a distro and package this vulnerability + occurrence was found in and its associated fix (if one is + available). + + Attributes: + affected_cpe_uri (str): + Required. The `CPE + URI `__ this + vulnerability was found in. + affected_package (str): + Required. The package this vulnerability was + found in. + affected_version (grafeas.grafeas_v1.types.Version): + Required. The version of the package that is + installed on the resource affected by this + vulnerability. + fixed_cpe_uri (str): + The `CPE URI `__ this + vulnerability was fixed in. It is possible for this to be + different from the affected_cpe_uri. + fixed_package (str): + The package this vulnerability was fixed in. It is possible + for this to be different from the affected_package. + fixed_version (grafeas.grafeas_v1.types.Version): + Required. The version of the package this + vulnerability was fixed in. Setting this to + VersionKind.MAXIMUM means no fix is yet + available. + fix_available (bool): + Output only. Whether a fix is available for + this package. + package_type (str): + The type of package (e.g. OS, MAVEN, GO). + effective_severity (grafeas.grafeas_v1.types.Severity): + The distro or language system assigned + severity for this vulnerability when that is + available and note provider assigned severity + when it is not available. + file_location (MutableSequence[grafeas.grafeas_v1.types.FileLocation]): + The location at which this package was found. + """ + + affected_cpe_uri: str = proto.Field( + proto.STRING, + number=1, + ) + affected_package: str = proto.Field( + proto.STRING, + number=2, + ) + affected_version: package.Version = proto.Field( + proto.MESSAGE, + number=3, + message=package.Version, + ) + fixed_cpe_uri: str = proto.Field( + proto.STRING, + number=4, + ) + fixed_package: str = proto.Field( + proto.STRING, + number=5, + ) + fixed_version: package.Version = proto.Field( + proto.MESSAGE, + number=6, + message=package.Version, + ) + fix_available: bool = proto.Field( + proto.BOOL, + number=7, + ) + package_type: str = proto.Field( + proto.STRING, + number=8, + ) + effective_severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=9, + enum=g_severity.Severity, + ) + file_location: MutableSequence[common.FileLocation] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=common.FileLocation, + ) + + class VexAssessment(proto.Message): + r"""VexAssessment provides all publisher provided Vex information + that is related to this vulnerability. + + Attributes: + cve (str): + Holds the MITRE standard Common Vulnerabilities and + Exposures (CVE) tracking number for the vulnerability. + Deprecated: Use vulnerability_id instead to denote CVEs. + vulnerability_id (str): + The vulnerability identifier for this + Assessment. Will hold one of common identifiers + e.g. CVE, GHSA etc. + related_uris (MutableSequence[grafeas.grafeas_v1.types.RelatedUrl]): + Holds a list of references associated with + this vulnerability item and assessment. + note_name (str): + The VulnerabilityAssessment note from which this + VexAssessment was generated. This will be of the form: + ``projects/[PROJECT_ID]/notes/[NOTE_ID]``. (-- api-linter: + core::0122::name-suffix=disabled aip.dev/not-precedent: The + suffix is kept for consistency. --) + state (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.State): + Provides the state of this Vulnerability + assessment. + impacts (MutableSequence[str]): + Contains information about the impact of this + vulnerability, this will change with time. + remediations (MutableSequence[grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Remediation]): + Specifies details on how to handle (and + presumably, fix) a vulnerability. + justification (grafeas.grafeas_v1.types.VulnerabilityAssessmentNote.Assessment.Justification): + Justification provides the justification when the state of + the assessment if NOT_AFFECTED. + """ + + cve: str = proto.Field( + proto.STRING, + number=1, + ) + vulnerability_id: str = proto.Field( + proto.STRING, + number=8, + ) + related_uris: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.RelatedUrl, + ) + note_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: vex.VulnerabilityAssessmentNote.Assessment.State = proto.Field( + proto.ENUM, + number=4, + enum=vex.VulnerabilityAssessmentNote.Assessment.State, + ) + impacts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + remediations: MutableSequence[ + vex.VulnerabilityAssessmentNote.Assessment.Remediation + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=vex.VulnerabilityAssessmentNote.Assessment.Remediation, + ) + justification: vex.VulnerabilityAssessmentNote.Assessment.Justification = ( + proto.Field( + proto.MESSAGE, + number=7, + message=vex.VulnerabilityAssessmentNote.Assessment.Justification, + ) + ) + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=2, + enum=g_severity.Severity, + ) + cvss_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + cvssv3: cvss.CVSS = proto.Field( + proto.MESSAGE, + number=10, + message=cvss.CVSS, + ) + package_issue: MutableSequence[PackageIssue] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=PackageIssue, + ) + short_description: str = proto.Field( + proto.STRING, + number=5, + ) + long_description: str = proto.Field( + proto.STRING, + number=6, + ) + related_urls: MutableSequence[common.RelatedUrl] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=common.RelatedUrl, + ) + effective_severity: g_severity.Severity = proto.Field( + proto.ENUM, + number=8, + enum=g_severity.Severity, + ) + fix_available: bool = proto.Field( + proto.BOOL, + number=9, + ) + cvss_version: cvss.CVSSVersion = proto.Field( + proto.ENUM, + number=11, + enum=cvss.CVSSVersion, + ) + cvss_v2: cvss.CVSS = proto.Field( + proto.MESSAGE, + number=12, + message=cvss.CVSS, + ) + vex_assessment: VexAssessment = proto.Field( + proto.MESSAGE, + number=13, + message=VexAssessment, + ) + extra_details: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/grafeas/mypy.ini b/packages/grafeas/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/packages/grafeas/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/packages/grafeas/noxfile.py b/packages/grafeas/noxfile.py new file mode 100644 index 000000000000..920f8c0eed03 --- /dev/null +++ b/packages/grafeas/noxfile.py @@ -0,0 +1,616 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "grafeas", "tests", "noxfile.py", "setup.py"] + +# Add samples to the list of directories to format if the directory exists. +if os.path.isdir("samples"): + LINT_PATHS.append("samples") + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", + "3.14", +] + +DEFAULT_PYTHON_VERSION = "3.14" + +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2450): +# Switch this to Python 3.15 alpha1 +# https://peps.python.org/pep-0790/ +PREVIEW_PYTHON_VERSION = "3.14" + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "grafeas" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ALL_PYTHON +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy + "mypy<1.16.0", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "grafeas", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "grafeas", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # 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", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): + # Remove this check once support for Protobuf 3.x is dropped. + if protobuf_implementation == "cpp" and session.python in ( + "3.11", + "3.12", + "3.13", + "3.14", + ): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=grafeas", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", # builder + "-d", + os.path.join("docs", "_build", "doctrees", ""), # cache directory + # paths to build: + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=PREVIEW_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): + # Remove this check once support for Protobuf 3.x is dropped. + if protobuf_implementation == "cpp" and session.python in ( + "3.11", + "3.12", + "3.13", + "3.14", + ): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py new file mode 100644 index 000000000000..d4dbb666e68a --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_notes(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py new file mode 100644 index 000000000000..bb47c162409a --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_batch_create_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_notes(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py new file mode 100644 index 000000000000..94bf30631275 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py new file mode 100644 index 000000000000..1a7d8c94f3d7 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreateOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_batch_create_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_create_occurrences(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py new file mode 100644 index 000000000000..a6f20ad35fd6 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = await client.create_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_CreateNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py new file mode 100644 index 000000000000..17f008cfc9b4 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_note_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_create_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Make the request + response = client.create_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_CreateNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py new file mode 100644 index 000000000000..c5e8655287ac --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_occurrence(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py new file mode 100644 index 000000000000..a7917a129f81 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_create_occurrence_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_create_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_occurrence(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py new file mode 100644 index 000000000000..de9803c48ca3 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + await client.delete_note(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py new file mode 100644 index 000000000000..ad68fec3afc4 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_note_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_delete_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteNoteRequest( + name="name_value", + ) + + # Make the request + client.delete_note(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py new file mode 100644 index 000000000000..7872f4448244 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + await client.delete_occurrence(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py new file mode 100644 index 000000000000..5786e6e336bd --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_delete_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.DeleteOccurrenceRequest( + name="name_value", + ) + + # Make the request + client.delete_occurrence(request=request) + + +# [END containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py new file mode 100644 index 000000000000..7382d5221d8f --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_GetNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py new file mode 100644 index 000000000000..e01d8954481b --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_note_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_get_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_GetNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py new file mode 100644 index 000000000000..95342437e6ee --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py new file mode 100644 index 000000000000..d6a5bcc7ddaf --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrenceNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_occurrence_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py new file mode 100644 index 000000000000..e95b8e53d000 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrenceNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_get_occurrence_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py new file mode 100644 index 000000000000..5f7e7278bf24 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_get_occurrence_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_get_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.GetOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.get_occurrence(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py new file mode 100644 index 000000000000..1113c13621c1 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNoteOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py new file mode 100644 index 000000000000..17595ad29d0d --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNoteOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_list_note_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNoteOccurrencesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_note_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py new file mode 100644 index 000000000000..fad196861bad --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNotes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_ListNotes_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py new file mode 100644 index 000000000000..0085885671e6 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_notes_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListNotes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListNotes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_list_notes(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListNotesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notes(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_ListNotes_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py new file mode 100644 index 000000000000..58b47a402faa --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py new file mode 100644 index 000000000000..6d4509711c33 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_list_occurrences_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListOccurrences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_list_occurrences(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.ListOccurrencesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_occurrences(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py new file mode 100644 index 000000000000..b2a97d0ddfe6 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateNote_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = await client.update_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_UpdateNote_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py new file mode 100644 index 000000000000..d317cda50836 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_note_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateNote +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateNote_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_update_note(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateNoteRequest( + name="name_value", + ) + + # Make the request + response = client.update_note(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_UpdateNote_sync] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py new file mode 100644 index 000000000000..6ff6ffa77959 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +async def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasAsyncClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = await client.update_occurrence(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async] diff --git a/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py new file mode 100644 index 000000000000..4a523c540c5a --- /dev/null +++ b/packages/grafeas/samples/generated_samples/containeranalysis_v1_generated_grafeas_update_occurrence_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateOccurrence +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install grafeas + + +# [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from grafeas import grafeas_v1 + + +def sample_update_occurrence(): + # Create a client + client = grafeas_v1.GrafeasClient() + + # Initialize request argument(s) + request = grafeas_v1.UpdateOccurrenceRequest( + name="name_value", + ) + + # Make the request + response = client.update_occurrence(request=request) + + # Handle the response + print(response) + + +# [END containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] diff --git a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json new file mode 100644 index 000000000000..7f54da166386 --- /dev/null +++ b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json @@ -0,0 +1,2353 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "grafeas.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "grafeas", + "version": "1.16.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notes", + "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", + "shortName": "batch_create_notes" + }, + "description": "Sample for BatchCreateNotes", + "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_batch_create_notes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notes", + "type": "MutableMapping[str, grafeas.grafeas_v1.types.Note]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateNotesResponse", + "shortName": "batch_create_notes" + }, + "description": "Sample for BatchCreateNotes", + "file": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_batch_create_notes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.batch_create_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrences", + "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", + "shortName": "batch_create_occurrences" + }, + "description": "Sample for BatchCreateOccurrences", + "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.batch_create_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.BatchCreateOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "BatchCreateOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.BatchCreateOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrences", + "type": "MutableSequence[grafeas.grafeas_v1.types.Occurrence]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.BatchCreateOccurrencesResponse", + "shortName": "batch_create_occurrences" + }, + "description": "Sample for BatchCreateOccurrences", + "file": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_batch_create_occurrences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_note", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateNoteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "note_id", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "create_note" + }, + "description": "Sample for CreateNote", + "file": "containeranalysis_v1_generated_grafeas_create_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_create_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.create_note", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateNoteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "note_id", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "create_note" + }, + "description": "Sample for CreateNote", + "file": "containeranalysis_v1_generated_grafeas_create_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateNote_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_create_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.create_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "create_occurrence" + }, + "description": "Sample for CreateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_create_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.create_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.CreateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "CreateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.CreateOccurrenceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "create_occurrence" + }, + "description": "Sample for CreateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_create_occurrence_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_note", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_note" + }, + "description": "Sample for DeleteNote", + "file": "containeranalysis_v1_generated_grafeas_delete_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_delete_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_note", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_note" + }, + "description": "Sample for DeleteNote", + "file": "containeranalysis_v1_generated_grafeas_delete_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteNote_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_delete_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.delete_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_occurrence" + }, + "description": "Sample for DeleteOccurrence", + "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_delete_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.delete_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.DeleteOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "DeleteOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.DeleteOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_occurrence" + }, + "description": "Sample for DeleteOccurrence", + "file": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_delete_occurrence_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "get_note" + }, + "description": "Sample for GetNote", + "file": "containeranalysis_v1_generated_grafeas_get_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_get_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.get_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "get_note" + }, + "description": "Sample for GetNote", + "file": "containeranalysis_v1_generated_grafeas_get_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetNote_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_get_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrenceNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "get_occurrence_note" + }, + "description": "Sample for GetOccurrenceNote", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_get_occurrence_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence_note", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrenceNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrenceNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "get_occurrence_note" + }, + "description": "Sample for GetOccurrenceNote", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_get_occurrence_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.get_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "get_occurrence" + }, + "description": "Sample for GetOccurrence", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_get_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.get_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.GetOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "GetOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.GetOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "get_occurrence" + }, + "description": "Sample for GetOccurrence", + "file": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_GetOccurrence_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_get_occurrence_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_note_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNoteOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesAsyncPager", + "shortName": "list_note_occurrences" + }, + "description": "Sample for ListNoteOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_list_note_occurrences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.list_note_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNoteOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNoteOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNoteOccurrencesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNoteOccurrencesPager", + "shortName": "list_note_occurrences" + }, + "description": "Sample for ListNoteOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_list_note_occurrences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesAsyncPager", + "shortName": "list_notes" + }, + "description": "Sample for ListNotes", + "file": "containeranalysis_v1_generated_grafeas_list_notes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_list_notes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.list_notes", + "method": { + "fullName": "grafeas.v1.Grafeas.ListNotes", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListNotes" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListNotesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListNotesPager", + "shortName": "list_notes" + }, + "description": "Sample for ListNotes", + "file": "containeranalysis_v1_generated_grafeas_list_notes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListNotes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_list_notes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.list_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesAsyncPager", + "shortName": "list_occurrences" + }, + "description": "Sample for ListOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_list_occurrences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.list_occurrences", + "method": { + "fullName": "grafeas.v1.Grafeas.ListOccurrences", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "ListOccurrences" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.ListOccurrencesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.services.grafeas.pagers.ListOccurrencesPager", + "shortName": "list_occurrences" + }, + "description": "Sample for ListOccurrences", + "file": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_ListOccurrences_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_list_occurrences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_note", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "update_note" + }, + "description": "Sample for UpdateNote", + "file": "containeranalysis_v1_generated_grafeas_update_note_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_update_note_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.update_note", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateNote", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateNote" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateNoteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "note", + "type": "grafeas.grafeas_v1.types.Note" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Note", + "shortName": "update_note" + }, + "description": "Sample for UpdateNote", + "file": "containeranalysis_v1_generated_grafeas_update_note_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateNote_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_update_note_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient", + "shortName": "GrafeasAsyncClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasAsyncClient.update_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "update_occurrence" + }, + "description": "Sample for UpdateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_update_occurrence_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "grafeas.grafeas_v1.GrafeasClient", + "shortName": "GrafeasClient" + }, + "fullName": "grafeas.grafeas_v1.GrafeasClient.update_occurrence", + "method": { + "fullName": "grafeas.v1.Grafeas.UpdateOccurrence", + "service": { + "fullName": "grafeas.v1.Grafeas", + "shortName": "Grafeas" + }, + "shortName": "UpdateOccurrence" + }, + "parameters": [ + { + "name": "request", + "type": "grafeas.grafeas_v1.types.UpdateOccurrenceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "occurrence", + "type": "grafeas.grafeas_v1.types.Occurrence" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "grafeas.grafeas_v1.types.Occurrence", + "shortName": "update_occurrence" + }, + "description": "Sample for UpdateOccurrence", + "file": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "containeranalysis_v1_generated_grafeas_update_occurrence_sync.py" + } + ] +} diff --git a/packages/grafeas/scripts/fixup_grafeas_v1_keywords.py b/packages/grafeas/scripts/fixup_grafeas_v1_keywords.py new file mode 100644 index 000000000000..6bb7b21dda4f --- /dev/null +++ b/packages/grafeas/scripts/fixup_grafeas_v1_keywords.py @@ -0,0 +1,189 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class grafeasCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_notes': ('parent', 'notes', ), + 'batch_create_occurrences': ('parent', 'occurrences', ), + 'create_note': ('parent', 'note_id', 'note', ), + 'create_occurrence': ('parent', 'occurrence', ), + 'delete_note': ('name', ), + 'delete_occurrence': ('name', ), + 'get_note': ('name', ), + 'get_occurrence': ('name', ), + 'get_occurrence_note': ('name', ), + 'list_note_occurrences': ('name', 'filter', 'page_size', 'page_token', ), + 'list_notes': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_occurrences': ('parent', 'filter', 'page_size', 'page_token', ), + 'update_note': ('name', 'note', 'update_mask', ), + 'update_occurrence': ('name', 'occurrence', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=grafeasCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the grafeas client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/grafeas/setup.py b/packages/grafeas/setup.py new file mode 100644 index 000000000000..6689233a0971 --- /dev/null +++ b/packages/grafeas/setup.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "grafeas" + + +description = "Grafeas API client library" + +version = None + +with open(os.path.join(package_root, "grafeas/grafeas/gapic_version.py")) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert len(version_candidates) == 1 + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "grpcio >= 1.33.2, < 2.0.0", + "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +extras = {} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("grafeas") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/grafeas/testing/constraints-3.10.txt b/packages/grafeas/testing/constraints-3.10.txt new file mode 100644 index 000000000000..93e6826f2af9 --- /dev/null +++ b/packages/grafeas/testing/constraints-3.10.txt @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf diff --git a/packages/grafeas/testing/constraints-3.11.txt b/packages/grafeas/testing/constraints-3.11.txt new file mode 100644 index 000000000000..93e6826f2af9 --- /dev/null +++ b/packages/grafeas/testing/constraints-3.11.txt @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf diff --git a/packages/grafeas/testing/constraints-3.12.txt b/packages/grafeas/testing/constraints-3.12.txt new file mode 100644 index 000000000000..93e6826f2af9 --- /dev/null +++ b/packages/grafeas/testing/constraints-3.12.txt @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf diff --git a/packages/grafeas/testing/constraints-3.13.txt b/packages/grafeas/testing/constraints-3.13.txt new file mode 100644 index 000000000000..1e93c60e50aa --- /dev/null +++ b/packages/grafeas/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +grpcio>=1 +proto-plus>=1 +protobuf>=6 diff --git a/packages/grafeas/testing/constraints-3.14.txt b/packages/grafeas/testing/constraints-3.14.txt new file mode 100644 index 000000000000..1e93c60e50aa --- /dev/null +++ b/packages/grafeas/testing/constraints-3.14.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +grpcio>=1 +proto-plus>=1 +protobuf>=6 diff --git a/packages/grafeas/testing/constraints-3.7.txt b/packages/grafeas/testing/constraints-3.7.txt new file mode 100644 index 000000000000..5d29dea38698 --- /dev/null +++ b/packages/grafeas/testing/constraints-3.7.txt @@ -0,0 +1,12 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2453) +# Add the minimum supported version of grpcio to constraints files +proto-plus==1.22.3 +protobuf==3.20.2 diff --git a/packages/grafeas/testing/constraints-3.8.txt b/packages/grafeas/testing/constraints-3.8.txt new file mode 100644 index 000000000000..93e6826f2af9 --- /dev/null +++ b/packages/grafeas/testing/constraints-3.8.txt @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf diff --git a/packages/grafeas/testing/constraints-3.9.txt b/packages/grafeas/testing/constraints-3.9.txt new file mode 100644 index 000000000000..93e6826f2af9 --- /dev/null +++ b/packages/grafeas/testing/constraints-3.9.txt @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +google-auth +grpcio +proto-plus +protobuf diff --git a/packages/grafeas/tests/__init__.py b/packages/grafeas/tests/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/grafeas/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/grafeas/tests/unit/__init__.py b/packages/grafeas/tests/unit/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/grafeas/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/grafeas/tests/unit/gapic/__init__.py b/packages/grafeas/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/grafeas/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py b/packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/grafeas/tests/unit/gapic/grafeas_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py b/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py new file mode 100644 index 000000000000..454c0fd5f768 --- /dev/null +++ b/packages/grafeas/tests/unit/gapic/grafeas_v1/test_grafeas.py @@ -0,0 +1,13188 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + +from grafeas.grafeas_v1.services.grafeas import ( + GrafeasAsyncClient, + GrafeasClient, + pagers, + transports, +) +from grafeas.grafeas_v1.types import ( + attestation, + build, + common, + compliance, + cvss, + deployment, + discovery, + dsse_attestation, + grafeas, + image, + intoto_provenance, + intoto_statement, + package, + provenance, + sbom, + secret, + severity, + slsa_provenance, + slsa_provenance_zero_two, + upgrade, + vex, + vulnerability, +) + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.GetOccurrenceRequest, + dict, + ], +) +def test_get_occurrence(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + response = client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +def test_get_occurrence_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.GetOccurrenceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceRequest( + name="name_value", + ) + + +def test_get_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_occurrence] = mock_rpc + request = {} + client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_occurrence_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_occurrence + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_occurrence + ] = mock_rpc + + request = {} + await client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_occurrence_async( + transport: str = "grpc_asyncio", request_type=grafeas.GetOccurrenceRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + ) + response = await client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +@pytest.mark.asyncio +async def test_get_occurrence_async_from_dict(): + await test_get_occurrence_async(request_type=dict) + + +def test_get_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.GetOccurrenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + call.return_value = grafeas.Occurrence() + client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetOccurrenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_occurrence( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_occurrence_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_occurrence( + grafeas.GetOccurrenceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_occurrence( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_occurrence( + grafeas.GetOccurrenceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.ListOccurrencesRequest, + dict, + ], +) +def test_list_occurrences(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.ListOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_occurrences_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.ListOccurrencesRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_occurrences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListOccurrencesRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + + +def test_list_occurrences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_occurrences + ] = mock_rpc + request = {} + client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_occurrences_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_occurrences + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_occurrences + ] = mock_rpc + + request = {} + await client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_occurrences_async( + transport: str = "grpc_asyncio", request_type=grafeas.ListOccurrencesRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListOccurrencesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.ListOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_occurrences_async_from_dict(): + await test_list_occurrences_async(request_type=dict) + + +def test_list_occurrences_field_headers(): + client = GrafeasClient( + 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 = grafeas.ListOccurrencesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + call.return_value = grafeas.ListOccurrencesResponse() + client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListOccurrencesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListOccurrencesResponse() + ) + await client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_occurrences( + parent="parent_value", + filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + + +def test_list_occurrences_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_occurrences( + grafeas.ListOccurrencesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_list_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListOccurrencesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_occurrences( + parent="parent_value", + filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_occurrences( + grafeas.ListOccurrencesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_occurrences_pager(transport_name: str = "grpc"): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_occurrences(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) for i in results) + + +def test_list_occurrences_pages(transport_name: str = "grpc"): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = list(client.list_occurrences(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_occurrences_async_pager(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_occurrences( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, grafeas.Occurrence) for i in responses) + + +@pytest.mark.asyncio +async def test_list_occurrences_async_pages(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_occurrences), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_occurrences(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.DeleteOccurrenceRequest, + dict, + ], +) +def test_delete_occurrence(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_occurrence_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.DeleteOccurrenceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteOccurrenceRequest( + name="name_value", + ) + + +def test_delete_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_occurrence + ] = mock_rpc + request = {} + client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_occurrence_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_occurrence + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_occurrence + ] = mock_rpc + + request = {} + await client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_occurrence_async( + transport: str = "grpc_asyncio", request_type=grafeas.DeleteOccurrenceRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteOccurrenceRequest() + 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_occurrence_async_from_dict(): + await test_delete_occurrence_async(request_type=dict) + + +def test_delete_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.DeleteOccurrenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + call.return_value = None + client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.DeleteOccurrenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_occurrence( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_occurrence_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_occurrence( + grafeas.DeleteOccurrenceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_occurrence( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_occurrence( + grafeas.DeleteOccurrenceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.CreateOccurrenceRequest, + dict, + ], +) +def test_create_occurrence(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + response = client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.CreateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +def test_create_occurrence_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.CreateOccurrenceRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateOccurrenceRequest( + parent="parent_value", + ) + + +def test_create_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_occurrence + ] = mock_rpc + request = {} + client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_occurrence_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_occurrence + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_occurrence + ] = mock_rpc + + request = {} + await client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_occurrence_async( + transport: str = "grpc_asyncio", request_type=grafeas.CreateOccurrenceRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + ) + response = await client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.CreateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +@pytest.mark.asyncio +async def test_create_occurrence_async_from_dict(): + await test_create_occurrence_async(request_type=dict) + + +def test_create_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.CreateOccurrenceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + call.return_value = grafeas.Occurrence() + client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.CreateOccurrenceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_occurrence( + parent="parent_value", + occurrence=grafeas.Occurrence(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].occurrence + mock_val = grafeas.Occurrence(name="name_value") + assert arg == mock_val + + +def test_create_occurrence_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_occurrence( + grafeas.CreateOccurrenceRequest(), + parent="parent_value", + occurrence=grafeas.Occurrence(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_occurrence( + parent="parent_value", + occurrence=grafeas.Occurrence(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].occurrence + mock_val = grafeas.Occurrence(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_occurrence( + grafeas.CreateOccurrenceRequest(), + parent="parent_value", + occurrence=grafeas.Occurrence(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.BatchCreateOccurrencesRequest, + dict, + ], +) +def test_batch_create_occurrences(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + response = client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +def test_batch_create_occurrences_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_create_occurrences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateOccurrencesRequest( + parent="parent_value", + ) + + +def test_batch_create_occurrences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_occurrences + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_occurrences + ] = mock_rpc + request = {} + client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_create_occurrences + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_create_occurrences + ] = mock_rpc + + request = {} + await client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_create_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async( + transport: str = "grpc_asyncio", request_type=grafeas.BatchCreateOccurrencesRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateOccurrencesResponse() + ) + response = await client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_async_from_dict(): + await test_batch_create_occurrences_async(request_type=dict) + + +def test_batch_create_occurrences_field_headers(): + client = GrafeasClient( + 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 = grafeas.BatchCreateOccurrencesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + call.return_value = grafeas.BatchCreateOccurrencesResponse() + client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.BatchCreateOccurrencesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateOccurrencesResponse() + ) + await client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_batch_create_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_occurrences( + parent="parent_value", + occurrences=[grafeas.Occurrence(name="name_value")], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].occurrences + mock_val = [grafeas.Occurrence(name="name_value")] + assert arg == mock_val + + +def test_batch_create_occurrences_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent="parent_value", + occurrences=[grafeas.Occurrence(name="name_value")], + ) + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateOccurrencesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_occurrences( + parent="parent_value", + occurrences=[grafeas.Occurrence(name="name_value")], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].occurrences + mock_val = [grafeas.Occurrence(name="name_value")] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent="parent_value", + occurrences=[grafeas.Occurrence(name="name_value")], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.UpdateOccurrenceRequest, + dict, + ], +) +def test_update_occurrence(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + response = client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +def test_update_occurrence_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.UpdateOccurrenceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_occurrence(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateOccurrenceRequest( + name="name_value", + ) + + +def test_update_occurrence_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_occurrence + ] = mock_rpc + request = {} + client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_occurrence_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_occurrence + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_occurrence + ] = mock_rpc + + request = {} + await client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_occurrence_async( + transport: str = "grpc_asyncio", request_type=grafeas.UpdateOccurrenceRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + ) + response = await client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateOccurrenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +@pytest.mark.asyncio +async def test_update_occurrence_async_from_dict(): + await test_update_occurrence_async(request_type=dict) + + +def test_update_occurrence_field_headers(): + client = GrafeasClient( + 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 = grafeas.UpdateOccurrenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + call.return_value = grafeas.Occurrence() + client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_occurrence_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.UpdateOccurrenceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + await client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_update_occurrence_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_occurrence( + name="name_value", + occurrence=grafeas.Occurrence(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].occurrence + mock_val = grafeas.Occurrence(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_occurrence_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_occurrence( + grafeas.UpdateOccurrenceRequest(), + name="name_value", + occurrence=grafeas.Occurrence(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_occurrence_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Occurrence() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Occurrence()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_occurrence( + name="name_value", + occurrence=grafeas.Occurrence(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].occurrence + mock_val = grafeas.Occurrence(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_occurrence_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_occurrence( + grafeas.UpdateOccurrenceRequest(), + name="name_value", + occurrence=grafeas.Occurrence(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.GetOccurrenceNoteRequest, + dict, + ], +) +def test_get_occurrence_note(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + response = client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +def test_get_occurrence_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.GetOccurrenceNoteRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_occurrence_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetOccurrenceNoteRequest( + name="name_value", + ) + + +def test_get_occurrence_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_occurrence_note in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_occurrence_note + ] = mock_rpc + request = {} + client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_occurrence_note_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_occurrence_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_occurrence_note + ] = mock_rpc + + request = {} + await client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_occurrence_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_occurrence_note_async( + transport: str = "grpc_asyncio", request_type=grafeas.GetOccurrenceNoteRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + response = await client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.GetOccurrenceNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.asyncio +async def test_get_occurrence_note_async_from_dict(): + await test_get_occurrence_note_async(request_type=dict) + + +def test_get_occurrence_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.GetOccurrenceNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + call.return_value = grafeas.Note() + client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_occurrence_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetOccurrenceNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_occurrence_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_occurrence_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_occurrence_note_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_occurrence_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_occurrence_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_occurrence_note_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.GetNoteRequest, + dict, + ], +) +def test_get_note(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + response = client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.GetNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +def test_get_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.GetNoteRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.GetNoteRequest( + name="name_value", + ) + + +def test_get_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_note] = mock_rpc + request = {} + client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_note_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_note + ] = mock_rpc + + request = {} + await client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_note_async( + transport: str = "grpc_asyncio", request_type=grafeas.GetNoteRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + response = await client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.GetNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.asyncio +async def test_get_note_async_from_dict(): + await test_get_note_async(request_type=dict) + + +def test_get_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.GetNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + call.return_value = grafeas.Note() + client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.GetNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_note_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_note( + grafeas.GetNoteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_note_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_note( + grafeas.GetNoteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.ListNotesRequest, + dict, + ], +) +def test_list_notes(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.ListNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_notes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.ListNotesRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_notes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNotesRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + + +def test_list_notes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_notes] = mock_rpc + request = {} + client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_notes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_notes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_notes + ] = mock_rpc + + request = {} + await client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_notes_async( + transport: str = "grpc_asyncio", request_type=grafeas.ListNotesRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNotesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.ListNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_notes_async_from_dict(): + await test_list_notes_async(request_type=dict) + + +def test_list_notes_field_headers(): + client = GrafeasClient( + 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 = grafeas.ListNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + call.return_value = grafeas.ListNotesResponse() + client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_notes_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNotesResponse() + ) + await client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_notes_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notes( + parent="parent_value", + filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + + +def test_list_notes_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_notes( + grafeas.ListNotesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_list_notes_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNotesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notes( + parent="parent_value", + filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_notes_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notes( + grafeas.ListNotesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_notes_pager(transport_name: str = "grpc"): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token="abc", + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token="def", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token="ghi", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_notes(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Note) for i in results) + + +def test_list_notes_pages(transport_name: str = "grpc"): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token="abc", + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token="def", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token="ghi", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notes(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_notes_async_pager(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token="abc", + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token="def", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token="ghi", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notes( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, grafeas.Note) for i in responses) + + +@pytest.mark.asyncio +async def test_list_notes_async_pages(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token="abc", + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token="def", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token="ghi", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_notes(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.DeleteNoteRequest, + dict, + ], +) +def test_delete_note(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.DeleteNoteRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.DeleteNoteRequest( + name="name_value", + ) + + +def test_delete_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_note] = mock_rpc + request = {} + client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_note_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_note + ] = mock_rpc + + request = {} + await client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_note_async( + transport: str = "grpc_asyncio", request_type=grafeas.DeleteNoteRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.DeleteNoteRequest() + 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_note_async_from_dict(): + await test_delete_note_async(request_type=dict) + + +def test_delete_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.DeleteNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + call.return_value = None + client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.DeleteNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_note_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_note( + grafeas.DeleteNoteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_note( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_note_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_note( + grafeas.DeleteNoteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.CreateNoteRequest, + dict, + ], +) +def test_create_note(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + response = client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.CreateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +def test_create_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.CreateNoteRequest( + parent="parent_value", + note_id="note_id_value", + ) + + +def test_create_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_note] = mock_rpc + request = {} + client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_note_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_note + ] = mock_rpc + + request = {} + await client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_note_async( + transport: str = "grpc_asyncio", request_type=grafeas.CreateNoteRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + response = await client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.CreateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.asyncio +async def test_create_note_async_from_dict(): + await test_create_note_async(request_type=dict) + + +def test_create_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.CreateNoteRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + call.return_value = grafeas.Note() + client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.CreateNoteRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_note( + parent="parent_value", + note_id="note_id_value", + note=grafeas.Note(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].note_id + mock_val = "note_id_value" + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(name="name_value") + assert arg == mock_val + + +def test_create_note_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_note( + grafeas.CreateNoteRequest(), + parent="parent_value", + note_id="note_id_value", + note=grafeas.Note(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_note( + parent="parent_value", + note_id="note_id_value", + note=grafeas.Note(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].note_id + mock_val = "note_id_value" + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_note_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_note( + grafeas.CreateNoteRequest(), + parent="parent_value", + note_id="note_id_value", + note=grafeas.Note(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.BatchCreateNotesRequest, + dict, + ], +) +def test_batch_create_notes(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + response = client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +def test_batch_create_notes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.BatchCreateNotesRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_create_notes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.BatchCreateNotesRequest( + parent="parent_value", + ) + + +def test_batch_create_notes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_notes in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_notes + ] = mock_rpc + request = {} + client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_create_notes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_create_notes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_create_notes + ] = mock_rpc + + request = {} + await client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_create_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_create_notes_async( + transport: str = "grpc_asyncio", request_type=grafeas.BatchCreateNotesRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateNotesResponse() + ) + response = await client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.BatchCreateNotesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +@pytest.mark.asyncio +async def test_batch_create_notes_async_from_dict(): + await test_batch_create_notes_async(request_type=dict) + + +def test_batch_create_notes_field_headers(): + client = GrafeasClient( + 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 = grafeas.BatchCreateNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + call.return_value = grafeas.BatchCreateNotesResponse() + client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_create_notes_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.BatchCreateNotesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateNotesResponse() + ) + await client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_batch_create_notes_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_notes( + parent="parent_value", + notes={"key_value": grafeas.Note(name="name_value")}, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].notes + mock_val = {"key_value": grafeas.Note(name="name_value")} + assert arg == mock_val + + +def test_batch_create_notes_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent="parent_value", + notes={"key_value": grafeas.Note(name="name_value")}, + ) + + +@pytest.mark.asyncio +async def test_batch_create_notes_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.BatchCreateNotesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateNotesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_notes( + parent="parent_value", + notes={"key_value": grafeas.Note(name="name_value")}, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].notes + mock_val = {"key_value": grafeas.Note(name="name_value")} + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_notes_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent="parent_value", + notes={"key_value": grafeas.Note(name="name_value")}, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.UpdateNoteRequest, + dict, + ], +) +def test_update_note(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + response = client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +def test_update_note_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.UpdateNoteRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_note(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.UpdateNoteRequest( + name="name_value", + ) + + +def test_update_note_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_note] = mock_rpc + request = {} + client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_note_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_note + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_note + ] = mock_rpc + + request = {} + await client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_note_async( + transport: str = "grpc_asyncio", request_type=grafeas.UpdateNoteRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + response = await client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.UpdateNoteRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.asyncio +async def test_update_note_async_from_dict(): + await test_update_note_async(request_type=dict) + + +def test_update_note_field_headers(): + client = GrafeasClient( + 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 = grafeas.UpdateNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + call.return_value = grafeas.Note() + client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_note_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.UpdateNoteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + await client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_update_note_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_note( + name="name_value", + note=grafeas.Note(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_note_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_note( + grafeas.UpdateNoteRequest(), + name="name_value", + note=grafeas.Note(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_note_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.Note() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(grafeas.Note()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_note( + name="name_value", + note=grafeas.Note(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].note + mock_val = grafeas.Note(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_note_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_note( + grafeas.UpdateNoteRequest(), + name="name_value", + note=grafeas.Note(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.ListNoteOccurrencesRequest, + dict, + ], +) +def test_list_note_occurrences(request_type, transport: str = "grpc"): + client = GrafeasClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grafeas.ListNoteOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_note_occurrences_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grafeas.ListNoteOccurrencesRequest( + name="name_value", + filter="filter_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_note_occurrences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grafeas.ListNoteOccurrencesRequest( + name="name_value", + filter="filter_value", + page_token="page_token_value", + ) + + +def test_list_note_occurrences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_note_occurrences + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_note_occurrences + ] = mock_rpc + request = {} + client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_note_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_note_occurrences + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_note_occurrences + ] = mock_rpc + + request = {} + await client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_note_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async( + transport: str = "grpc_asyncio", request_type=grafeas.ListNoteOccurrencesRequest +): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNoteOccurrencesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grafeas.ListNoteOccurrencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_from_dict(): + await test_list_note_occurrences_async(request_type=dict) + + +def test_list_note_occurrences_field_headers(): + client = GrafeasClient( + 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 = grafeas.ListNoteOccurrencesRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + call.return_value = grafeas.ListNoteOccurrencesResponse() + client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_note_occurrences_field_headers_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grafeas.ListNoteOccurrencesRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNoteOccurrencesResponse() + ) + await client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_list_note_occurrences_flattened(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_note_occurrences( + name="name_value", + filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + + +def test_list_note_occurrences_flattened_error(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name="name_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_list_note_occurrences_flattened_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grafeas.ListNoteOccurrencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNoteOccurrencesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_note_occurrences( + name="name_value", + filter="filter_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_note_occurrences_flattened_error_async(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name="name_value", + filter="filter_value", + ) + + +def test_list_note_occurrences_pager(transport_name: str = "grpc"): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_note_occurrences(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) for i in results) + + +def test_list_note_occurrences_pages(transport_name: str = "grpc"): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = list(client.list_note_occurrences(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_pager(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_note_occurrences( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, grafeas.Occurrence) for i in responses) + + +@pytest.mark.asyncio +async def test_list_note_occurrences_async_pages(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_note_occurrences(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_occurrence_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_occurrence] = mock_rpc + + request = {} + client.get_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_occurrence_rest_required_fields(request_type=grafeas.GetOccurrenceRequest): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_occurrence._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_occurrence._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Occurrence() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_occurrence(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Occurrence() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/occurrences/sample2"} + + # 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 + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_occurrence(**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/*/occurrences/*}" % client.transport._host, args[1] + ) + + +def test_get_occurrence_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_occurrence( + grafeas.GetOccurrenceRequest(), + name="name_value", + ) + + +def test_list_occurrences_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_occurrences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_occurrences + ] = mock_rpc + + request = {} + client.list_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_occurrences_rest_required_fields( + request_type=grafeas.ListOccurrencesRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_occurrences._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_occurrences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.ListOccurrencesResponse() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.ListOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_occurrences(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_occurrences_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_occurrences._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_occurrences_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.ListOccurrencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + filter="filter_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.ListOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_occurrences(**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/*}/occurrences" % client.transport._host, args[1] + ) + + +def test_list_occurrences_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_occurrences( + grafeas.ListOccurrencesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_occurrences_rest_pager(transport: str = "rest"): + client = GrafeasClient( + 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 = ( + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grafeas.ListOccurrencesResponse.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"} + + pager = client.list_occurrences(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) for i in results) + + pages = list(client.list_occurrences(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_occurrence_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_occurrence + ] = mock_rpc + + request = {} + client.delete_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_occurrence_rest_required_fields( + request_type=grafeas.DeleteOccurrenceRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_occurrence._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_occurrence._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_occurrence(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/occurrences/sample2"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_occurrence(**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/*/occurrences/*}" % client.transport._host, args[1] + ) + + +def test_delete_occurrence_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_occurrence( + grafeas.DeleteOccurrenceRequest(), + name="name_value", + ) + + +def test_create_occurrence_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_occurrence + ] = mock_rpc + + request = {} + client.create_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_occurrence_rest_required_fields( + request_type=grafeas.CreateOccurrenceRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_occurrence._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_occurrence._get_unset_required_fields(jsonified_request) + 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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Occurrence() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_occurrence(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "occurrence", + ) + ) + ) + + +def test_create_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Occurrence() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + occurrence=grafeas.Occurrence(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_occurrence(**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/*}/occurrences" % client.transport._host, args[1] + ) + + +def test_create_occurrence_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_occurrence( + grafeas.CreateOccurrenceRequest(), + parent="parent_value", + occurrence=grafeas.Occurrence(name="name_value"), + ) + + +def test_batch_create_occurrences_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_occurrences + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_occurrences + ] = mock_rpc + + request = {} + client.batch_create_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_create_occurrences_rest_required_fields( + request_type=grafeas.BatchCreateOccurrencesRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_create_occurrences._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() + ).batch_create_occurrences._get_unset_required_fields(jsonified_request) + 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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.BatchCreateOccurrencesResponse() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.BatchCreateOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_create_occurrences(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_create_occurrences_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_create_occurrences._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "occurrences", + ) + ) + ) + + +def test_batch_create_occurrences_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.BatchCreateOccurrencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + occurrences=[grafeas.Occurrence(name="name_value")], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.BatchCreateOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_create_occurrences(**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/*}/occurrences:batchCreate" + % client.transport._host, + args[1], + ) + + +def test_batch_create_occurrences_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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.batch_create_occurrences( + grafeas.BatchCreateOccurrencesRequest(), + parent="parent_value", + occurrences=[grafeas.Occurrence(name="name_value")], + ) + + +def test_update_occurrence_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_occurrence in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_occurrence + ] = mock_rpc + + request = {} + client.update_occurrence(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_occurrence(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_occurrence_rest_required_fields( + request_type=grafeas.UpdateOccurrenceRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_occurrence._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() + ).update_occurrence._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + 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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Occurrence() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_occurrence(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_occurrence_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_occurrence._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "name", + "occurrence", + ) + ) + ) + + +def test_update_occurrence_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Occurrence() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/occurrences/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + occurrence=grafeas.Occurrence(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 + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_occurrence(**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/*/occurrences/*}" % client.transport._host, args[1] + ) + + +def test_update_occurrence_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_occurrence( + grafeas.UpdateOccurrenceRequest(), + name="name_value", + occurrence=grafeas.Occurrence(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_occurrence_note_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_occurrence_note in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_occurrence_note + ] = mock_rpc + + request = {} + client.get_occurrence_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_occurrence_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_occurrence_note_rest_required_fields( + request_type=grafeas.GetOccurrenceNoteRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_occurrence_note._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_occurrence_note._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_occurrence_note(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_occurrence_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_occurrence_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_occurrence_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/occurrences/sample2"} + + # 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 + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_occurrence_note(**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/*/occurrences/*}/notes" % client.transport._host, + args[1], + ) + + +def test_get_occurrence_note_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_occurrence_note( + grafeas.GetOccurrenceNoteRequest(), + name="name_value", + ) + + +def test_get_note_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_note] = mock_rpc + + request = {} + client.get_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_note_rest_required_fields(request_type=grafeas.GetNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_note._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_note._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_note(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/notes/sample2"} + + # 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 + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_note(**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/*/notes/*}" % client.transport._host, args[1] + ) + + +def test_get_note_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_note( + grafeas.GetNoteRequest(), + name="name_value", + ) + + +def test_list_notes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_notes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_notes] = mock_rpc + + request = {} + client.list_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_notes_rest_required_fields(request_type=grafeas.ListNotesRequest): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_notes._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_notes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.ListNotesResponse() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.ListNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_notes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_notes_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_notes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_notes_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.ListNotesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + filter="filter_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.ListNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_notes(**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/*}/notes" % client.transport._host, args[1] + ) + + +def test_list_notes_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_notes( + grafeas.ListNotesRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_notes_rest_pager(transport: str = "rest"): + client = GrafeasClient( + 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 = ( + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + grafeas.Note(), + ], + next_page_token="abc", + ), + grafeas.ListNotesResponse( + notes=[], + next_page_token="def", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + ], + next_page_token="ghi", + ), + grafeas.ListNotesResponse( + notes=[ + grafeas.Note(), + grafeas.Note(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(grafeas.ListNotesResponse.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"} + + pager = client.list_notes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Note) for i in results) + + pages = list(client.list_notes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_note_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_note] = mock_rpc + + request = {} + client.delete_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_note_rest_required_fields(request_type=grafeas.DeleteNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_note._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_note._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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_note(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_note._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_note_rest_flattened(): + client = GrafeasClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/notes/sample2"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_note(**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/*/notes/*}" % client.transport._host, args[1] + ) + + +def test_delete_note_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_note( + grafeas.DeleteNoteRequest(), + name="name_value", + ) + + +def test_create_note_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_note] = mock_rpc + + request = {} + client.create_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_note_rest_required_fields(request_type=grafeas.CreateNoteRequest): + transport_class = transports.GrafeasRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["note_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "noteId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_note._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "noteId" in jsonified_request + assert jsonified_request["noteId"] == request_init["note_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["noteId"] = "note_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_note._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("note_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 "noteId" in jsonified_request + assert jsonified_request["noteId"] == "note_id_value" + + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_note(request) + + expected_params = [ + ( + "noteId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_note._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("noteId",)) + & set( + ( + "parent", + "noteId", + "note", + ) + ) + ) + + +def test_create_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + note_id="note_id_value", + note=grafeas.Note(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_note(**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/*}/notes" % client.transport._host, args[1] + ) + + +def test_create_note_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_note( + grafeas.CreateNoteRequest(), + parent="parent_value", + note_id="note_id_value", + note=grafeas.Note(name="name_value"), + ) + + +def test_batch_create_notes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_notes in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_notes + ] = mock_rpc + + request = {} + client.batch_create_notes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_notes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_create_notes_rest_required_fields( + request_type=grafeas.BatchCreateNotesRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_create_notes._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() + ).batch_create_notes._get_unset_required_fields(jsonified_request) + 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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.BatchCreateNotesResponse() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.BatchCreateNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_create_notes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_create_notes_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_create_notes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "notes", + ) + ) + ) + + +def test_batch_create_notes_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.BatchCreateNotesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + notes={"key_value": grafeas.Note(name="name_value")}, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.BatchCreateNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_create_notes(**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/*}/notes:batchCreate" % client.transport._host, + args[1], + ) + + +def test_batch_create_notes_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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.batch_create_notes( + grafeas.BatchCreateNotesRequest(), + parent="parent_value", + notes={"key_value": grafeas.Note(name="name_value")}, + ) + + +def test_update_note_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_note in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_note] = mock_rpc + + request = {} + client.update_note(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_note(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_note_rest_required_fields(request_type=grafeas.UpdateNoteRequest): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_note._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() + ).update_note._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + 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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.Note() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_note(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_note_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_note._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "name", + "note", + ) + ) + ) + + +def test_update_note_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.Note() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/notes/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + note=grafeas.Note(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 + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_note(**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/*/notes/*}" % client.transport._host, args[1] + ) + + +def test_update_note_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_note( + grafeas.UpdateNoteRequest(), + name="name_value", + note=grafeas.Note(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_list_note_occurrences_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_note_occurrences + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_note_occurrences + ] = mock_rpc + + request = {} + client.list_note_occurrences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_note_occurrences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_note_occurrences_rest_required_fields( + request_type=grafeas.ListNoteOccurrencesRequest, +): + transport_class = transports.GrafeasRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_note_occurrences._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() + ).list_note_occurrences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + 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 = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grafeas.ListNoteOccurrencesResponse() + # 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 + + # Convert return value to protobuf type + return_value = grafeas.ListNoteOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_note_occurrences(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_note_occurrences_rest_unset_required_fields(): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_note_occurrences._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("name",)) + ) + + +def test_list_note_occurrences_rest_flattened(): + client = GrafeasClient( + 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 = grafeas.ListNoteOccurrencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/notes/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + filter="filter_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = grafeas.ListNoteOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_note_occurrences(**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/*/notes/*}/occurrences" % client.transport._host, + args[1], + ) + + +def test_list_note_occurrences_rest_flattened_error(transport: str = "rest"): + client = GrafeasClient( + 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_note_occurrences( + grafeas.ListNoteOccurrencesRequest(), + name="name_value", + filter="filter_value", + ) + + +def test_list_note_occurrences_rest_pager(transport: str = "rest"): + client = GrafeasClient( + 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 = ( + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + next_page_token="abc", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[], + next_page_token="def", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + ], + next_page_token="ghi", + ), + grafeas.ListNoteOccurrencesResponse( + occurrences=[ + grafeas.Occurrence(), + grafeas.Occurrence(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + grafeas.ListNoteOccurrencesResponse.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 = {"name": "projects/sample1/notes/sample2"} + + pager = client.list_note_occurrences(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, grafeas.Occurrence) for i in results) + + pages = list(client.list_note_occurrences(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GrafeasClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GrafeasGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GrafeasGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + transports.GrafeasRestTransport, + ], +) +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_transport_kind_grpc(): + transport = GrafeasClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + call.return_value = grafeas.Occurrence() + client.get_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_occurrences_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + call.return_value = grafeas.ListOccurrencesResponse() + client.list_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListOccurrencesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + call.return_value = None + client.delete_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + call.return_value = grafeas.Occurrence() + client.create_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_occurrences_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + call.return_value = grafeas.BatchCreateOccurrencesResponse() + client.batch_create_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateOccurrencesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_occurrence_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + call.return_value = grafeas.Occurrence() + client.update_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_occurrence_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + call.return_value = grafeas.Note() + client.get_occurrence_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + call.return_value = grafeas.Note() + client.get_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_notes_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + call.return_value = grafeas.ListNotesResponse() + client.list_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNotesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + call.return_value = None + client.delete_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + call.return_value = grafeas.Note() + client.create_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_notes_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + call.return_value = grafeas.BatchCreateNotesResponse() + client.batch_create_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateNotesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_note_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + call.return_value = grafeas.Note() + client.update_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_note_occurrences_empty_call_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + call.return_value = grafeas.ListNoteOccurrencesResponse() + client.list_note_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNoteOccurrencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GrafeasAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + ) + await client.get_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_occurrences_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListOccurrencesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListOccurrencesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + ) + await client.create_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_create_occurrences_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateOccurrencesResponse() + ) + await client.batch_create_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateOccurrencesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_occurrence_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + ) + await client.update_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_occurrence_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + await client.get_occurrence_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + await client.get_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_notes_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNotesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNotesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + await client.create_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_create_notes_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.BatchCreateNotesResponse() + ) + await client.batch_create_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateNotesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_note_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + ) + await client.update_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_note_occurrences_empty_call_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grafeas.ListNoteOccurrencesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_note_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNoteOccurrencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GrafeasClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_occurrence_rest_bad_request(request_type=grafeas.GetOccurrenceRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_occurrence(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.GetOccurrenceRequest, + dict, + ], +) +def test_get_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_get_occurrence" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_get_occurrence_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_get_occurrence" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.GetOccurrenceRequest.pb(grafeas.GetOccurrenceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Occurrence.to_json(grafeas.Occurrence()) + req.return_value.content = return_value + + request = grafeas.GetOccurrenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Occurrence() + post_with_metadata.return_value = grafeas.Occurrence(), metadata + + client.get_occurrence( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_occurrences_rest_bad_request(request_type=grafeas.ListOccurrencesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_occurrences(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.ListOccurrencesRequest, + dict, + ], +) +def test_list_occurrences_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = grafeas.ListOccurrencesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.ListOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_occurrences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOccurrencesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_occurrences_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_list_occurrences" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_list_occurrences_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_list_occurrences" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.ListOccurrencesRequest.pb(grafeas.ListOccurrencesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.ListOccurrencesResponse.to_json( + grafeas.ListOccurrencesResponse() + ) + req.return_value.content = return_value + + request = grafeas.ListOccurrencesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.ListOccurrencesResponse() + post_with_metadata.return_value = grafeas.ListOccurrencesResponse(), metadata + + client.list_occurrences( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_occurrence_rest_bad_request( + request_type=grafeas.DeleteOccurrenceRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_occurrence(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.DeleteOccurrenceRequest, + dict, + ], +) +def test_delete_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_occurrence(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "pre_delete_occurrence" + ) as pre: + pre.assert_not_called() + pb_message = grafeas.DeleteOccurrenceRequest.pb( + grafeas.DeleteOccurrenceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = grafeas.DeleteOccurrenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_occurrence( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_occurrence_rest_bad_request( + request_type=grafeas.CreateOccurrenceRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_occurrence(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.CreateOccurrenceRequest, + dict, + ], +) +def test_create_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["occurrence"] = { + "name": "name_value", + "resource_uri": "resource_uri_value", + "note_name": "note_name_value", + "kind": 1, + "remediation": "remediation_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "vulnerability": { + "type_": "type__value", + "severity": 1, + "cvss_score": 0.1082, + "cvssv3": { + "base_score": 0.1046, + "exploitability_score": 0.21580000000000002, + "impact_score": 0.1273, + "attack_vector": 1, + "attack_complexity": 1, + "authentication": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + "package_issue": [ + { + "affected_cpe_uri": "affected_cpe_uri_value", + "affected_package": "affected_package_value", + "affected_version": { + "epoch": 527, + "name": "name_value", + "revision": "revision_value", + "inclusive": True, + "kind": 1, + "full_name": "full_name_value", + }, + "fixed_cpe_uri": "fixed_cpe_uri_value", + "fixed_package": "fixed_package_value", + "fixed_version": {}, + "fix_available": True, + "package_type": "package_type_value", + "effective_severity": 1, + "file_location": [ + { + "file_path": "file_path_value", + "layer_details": { + "index": 536, + "diff_id": "diff_id_value", + "chain_id": "chain_id_value", + "command": "command_value", + "base_images": [ + { + "name": "name_value", + "repository": "repository_value", + "layer_count": 1189, + } + ], + }, + } + ], + } + ], + "short_description": "short_description_value", + "long_description": "long_description_value", + "related_urls": [{"url": "url_value", "label": "label_value"}], + "effective_severity": 1, + "fix_available": True, + "cvss_version": 1, + "cvss_v2": {}, + "vex_assessment": { + "cve": "cve_value", + "vulnerability_id": "vulnerability_id_value", + "related_uris": {}, + "note_name": "note_name_value", + "state": 1, + "impacts": ["impacts_value1", "impacts_value2"], + "remediations": [ + { + "remediation_type": 1, + "details": "details_value", + "remediation_uri": {}, + } + ], + "justification": {"justification_type": 1, "details": "details_value"}, + }, + "extra_details": "extra_details_value", + }, + "build": { + "provenance": { + "id": "id_value", + "project_id": "project_id_value", + "commands": [ + { + "name": "name_value", + "env": ["env_value1", "env_value2"], + "args": ["args_value1", "args_value2"], + "dir_": "dir__value", + "id": "id_value", + "wait_for": ["wait_for_value1", "wait_for_value2"], + } + ], + "built_artifacts": [ + { + "checksum": "checksum_value", + "id": "id_value", + "names": ["names_value1", "names_value2"], + } + ], + "create_time": {}, + "start_time": {}, + "end_time": {}, + "creator": "creator_value", + "logs_uri": "logs_uri_value", + "source_provenance": { + "artifact_storage_source_uri": "artifact_storage_source_uri_value", + "file_hashes": {}, + "context": { + "cloud_repo": { + "repo_id": { + "project_repo_id": { + "project_id": "project_id_value", + "repo_name": "repo_name_value", + }, + "uid": "uid_value", + }, + "revision_id": "revision_id_value", + "alias_context": {"kind": 1, "name": "name_value"}, + }, + "gerrit": { + "host_uri": "host_uri_value", + "gerrit_project": "gerrit_project_value", + "revision_id": "revision_id_value", + "alias_context": {}, + }, + "git": {"url": "url_value", "revision_id": "revision_id_value"}, + "labels": {}, + }, + "additional_contexts": {}, + }, + "trigger_id": "trigger_id_value", + "build_options": {}, + "builder_version": "builder_version_value", + }, + "provenance_bytes": "provenance_bytes_value", + "intoto_provenance": { + "builder_config": {"id": "id_value"}, + "recipe": { + "type_": "type__value", + "defined_in_material": 1971, + "entry_point": "entry_point_value", + "arguments": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + "environment": {}, + }, + "metadata": { + "build_invocation_id": "build_invocation_id_value", + "build_started_on": {}, + "build_finished_on": {}, + "completeness": { + "arguments": True, + "environment": True, + "materials": True, + }, + "reproducible": True, + }, + "materials": ["materials_value1", "materials_value2"], + }, + "intoto_statement": { + "type_": "type__value", + "subject": [{"name": "name_value", "digest": {}}], + "predicate_type": "predicate_type_value", + "provenance": {}, + "slsa_provenance": { + "builder": {"id": "id_value"}, + "recipe": { + "type_": "type__value", + "defined_in_material": 1971, + "entry_point": "entry_point_value", + "arguments": {}, + "environment": {}, + }, + "metadata": { + "build_invocation_id": "build_invocation_id_value", + "build_started_on": {}, + "build_finished_on": {}, + "completeness": { + "arguments": True, + "environment": True, + "materials": True, + }, + "reproducible": True, + }, + "materials": [{"uri": "uri_value", "digest": {}}], + }, + "slsa_provenance_zero_two": { + "builder": {"id": "id_value"}, + "build_type": "build_type_value", + "invocation": { + "config_source": { + "uri": "uri_value", + "digest": {}, + "entry_point": "entry_point_value", + }, + "parameters": {"fields": {}}, + "environment": {}, + }, + "build_config": {}, + "metadata": { + "build_invocation_id": "build_invocation_id_value", + "build_started_on": {}, + "build_finished_on": {}, + "completeness": { + "parameters": True, + "environment": True, + "materials": True, + }, + "reproducible": True, + }, + "materials": [{"uri": "uri_value", "digest": {}}], + }, + }, + "in_toto_slsa_provenance_v1": { + "type_": "type__value", + "subject": {}, + "predicate_type": "predicate_type_value", + "predicate": { + "build_definition": { + "build_type": "build_type_value", + "external_parameters": {}, + "internal_parameters": {}, + "resolved_dependencies": [ + { + "name": "name_value", + "uri": "uri_value", + "digest": {}, + "content": b"content_blob", + "download_location": "download_location_value", + "media_type": "media_type_value", + "annotations": {}, + } + ], + }, + "run_details": { + "builder": { + "id": "id_value", + "version": {}, + "builder_dependencies": {}, + }, + "metadata": { + "invocation_id": "invocation_id_value", + "started_on": {}, + "finished_on": {}, + }, + "byproducts": {}, + }, + }, + }, + }, + "image": { + "fingerprint": { + "v1_name": "v1_name_value", + "v2_blob": ["v2_blob_value1", "v2_blob_value2"], + "v2_name": "v2_name_value", + }, + "distance": 843, + "layer_info": [ + {"directive": "directive_value", "arguments": "arguments_value"} + ], + "base_resource_url": "base_resource_url_value", + }, + "package": { + "name": "name_value", + "location": [ + {"cpe_uri": "cpe_uri_value", "version": {}, "path": "path_value"} + ], + "package_type": "package_type_value", + "cpe_uri": "cpe_uri_value", + "architecture": 1, + "license_": { + "expression": "expression_value", + "comments": "comments_value", + }, + "version": {}, + }, + "deployment": { + "user_email": "user_email_value", + "deploy_time": {}, + "undeploy_time": {}, + "config": "config_value", + "address": "address_value", + "resource_uri": ["resource_uri_value1", "resource_uri_value2"], + "platform": 1, + }, + "discovery": { + "continuous_analysis": 1, + "analysis_status": 1, + "analysis_completed": { + "analysis_type": ["analysis_type_value1", "analysis_type_value2"] + }, + "analysis_error": [ + {"code": 411, "message": "message_value", "details": {}} + ], + "analysis_status_error": {}, + "cpe": "cpe_value", + "last_scan_time": {}, + "archive_time": {}, + "sbom_status": {"sbom_state": 1, "error": "error_value"}, + "vulnerability_attestation": { + "last_attempt_time": {}, + "state": 1, + "error": "error_value", + }, + }, + "attestation": { + "serialized_payload": b"serialized_payload_blob", + "signatures": [ + {"signature": b"signature_blob", "public_key_id": "public_key_id_value"} + ], + "jwts": [{"compact_jwt": "compact_jwt_value"}], + }, + "upgrade": { + "package": "package_value", + "parsed_version": {}, + "distribution": { + "cpe_uri": "cpe_uri_value", + "classification": "classification_value", + "severity": "severity_value", + "cve": ["cve_value1", "cve_value2"], + }, + "windows_update": { + "identity": {"update_id": "update_id_value", "revision": 879}, + "title": "title_value", + "description": "description_value", + "categories": [ + {"category_id": "category_id_value", "name": "name_value"} + ], + "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], + "support_url": "support_url_value", + "last_published_timestamp": {}, + }, + }, + "compliance": { + "non_compliant_files": [ + { + "path": "path_value", + "display_command": "display_command_value", + "reason": "reason_value", + } + ], + "non_compliance_reason": "non_compliance_reason_value", + "version": { + "cpe_uri": "cpe_uri_value", + "benchmark_document": "benchmark_document_value", + "version": "version_value", + }, + }, + "dsse_attestation": { + "envelope": { + "payload": b"payload_blob", + "payload_type": "payload_type_value", + "signatures": [{"sig": b"sig_blob", "keyid": "keyid_value"}], + }, + "statement": {}, + }, + "sbom_reference": { + "payload": { + "type_": "type__value", + "predicate_type": "predicate_type_value", + "subject": {}, + "predicate": { + "referrer_id": "referrer_id_value", + "location": "location_value", + "mime_type": "mime_type_value", + "digest": {}, + }, + }, + "payload_type": "payload_type_value", + "signatures": {}, + }, + "secret": { + "kind": 1, + "locations": [{"file_location": {}}], + "statuses": [{"status": 1, "update_time": {}, "message": "message_value"}], + }, + "envelope": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = grafeas.CreateOccurrenceRequest.meta.fields["occurrence"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["occurrence"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["occurrence"][field])): + del request_init["occurrence"][field][i][subfield] + else: + del request_init["occurrence"][field][subfield] + 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 = grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_create_occurrence" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_create_occurrence_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_create_occurrence" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.CreateOccurrenceRequest.pb( + grafeas.CreateOccurrenceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Occurrence.to_json(grafeas.Occurrence()) + req.return_value.content = return_value + + request = grafeas.CreateOccurrenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Occurrence() + post_with_metadata.return_value = grafeas.Occurrence(), metadata + + client.create_occurrence( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_create_occurrences_rest_bad_request( + request_type=grafeas.BatchCreateOccurrencesRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_create_occurrences(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.BatchCreateOccurrencesRequest, + dict, + ], +) +def test_batch_create_occurrences_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = grafeas.BatchCreateOccurrencesResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.BatchCreateOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_occurrences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateOccurrencesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_occurrences_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_batch_create_occurrences" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_batch_create_occurrences_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_batch_create_occurrences" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.BatchCreateOccurrencesRequest.pb( + grafeas.BatchCreateOccurrencesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.BatchCreateOccurrencesResponse.to_json( + grafeas.BatchCreateOccurrencesResponse() + ) + req.return_value.content = return_value + + request = grafeas.BatchCreateOccurrencesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.BatchCreateOccurrencesResponse() + post_with_metadata.return_value = ( + grafeas.BatchCreateOccurrencesResponse(), + metadata, + ) + + client.batch_create_occurrences( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_occurrence_rest_bad_request( + request_type=grafeas.UpdateOccurrenceRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_occurrence(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.UpdateOccurrenceRequest, + dict, + ], +) +def test_update_occurrence_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/sample2"} + request_init["occurrence"] = { + "name": "name_value", + "resource_uri": "resource_uri_value", + "note_name": "note_name_value", + "kind": 1, + "remediation": "remediation_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "vulnerability": { + "type_": "type__value", + "severity": 1, + "cvss_score": 0.1082, + "cvssv3": { + "base_score": 0.1046, + "exploitability_score": 0.21580000000000002, + "impact_score": 0.1273, + "attack_vector": 1, + "attack_complexity": 1, + "authentication": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + "package_issue": [ + { + "affected_cpe_uri": "affected_cpe_uri_value", + "affected_package": "affected_package_value", + "affected_version": { + "epoch": 527, + "name": "name_value", + "revision": "revision_value", + "inclusive": True, + "kind": 1, + "full_name": "full_name_value", + }, + "fixed_cpe_uri": "fixed_cpe_uri_value", + "fixed_package": "fixed_package_value", + "fixed_version": {}, + "fix_available": True, + "package_type": "package_type_value", + "effective_severity": 1, + "file_location": [ + { + "file_path": "file_path_value", + "layer_details": { + "index": 536, + "diff_id": "diff_id_value", + "chain_id": "chain_id_value", + "command": "command_value", + "base_images": [ + { + "name": "name_value", + "repository": "repository_value", + "layer_count": 1189, + } + ], + }, + } + ], + } + ], + "short_description": "short_description_value", + "long_description": "long_description_value", + "related_urls": [{"url": "url_value", "label": "label_value"}], + "effective_severity": 1, + "fix_available": True, + "cvss_version": 1, + "cvss_v2": {}, + "vex_assessment": { + "cve": "cve_value", + "vulnerability_id": "vulnerability_id_value", + "related_uris": {}, + "note_name": "note_name_value", + "state": 1, + "impacts": ["impacts_value1", "impacts_value2"], + "remediations": [ + { + "remediation_type": 1, + "details": "details_value", + "remediation_uri": {}, + } + ], + "justification": {"justification_type": 1, "details": "details_value"}, + }, + "extra_details": "extra_details_value", + }, + "build": { + "provenance": { + "id": "id_value", + "project_id": "project_id_value", + "commands": [ + { + "name": "name_value", + "env": ["env_value1", "env_value2"], + "args": ["args_value1", "args_value2"], + "dir_": "dir__value", + "id": "id_value", + "wait_for": ["wait_for_value1", "wait_for_value2"], + } + ], + "built_artifacts": [ + { + "checksum": "checksum_value", + "id": "id_value", + "names": ["names_value1", "names_value2"], + } + ], + "create_time": {}, + "start_time": {}, + "end_time": {}, + "creator": "creator_value", + "logs_uri": "logs_uri_value", + "source_provenance": { + "artifact_storage_source_uri": "artifact_storage_source_uri_value", + "file_hashes": {}, + "context": { + "cloud_repo": { + "repo_id": { + "project_repo_id": { + "project_id": "project_id_value", + "repo_name": "repo_name_value", + }, + "uid": "uid_value", + }, + "revision_id": "revision_id_value", + "alias_context": {"kind": 1, "name": "name_value"}, + }, + "gerrit": { + "host_uri": "host_uri_value", + "gerrit_project": "gerrit_project_value", + "revision_id": "revision_id_value", + "alias_context": {}, + }, + "git": {"url": "url_value", "revision_id": "revision_id_value"}, + "labels": {}, + }, + "additional_contexts": {}, + }, + "trigger_id": "trigger_id_value", + "build_options": {}, + "builder_version": "builder_version_value", + }, + "provenance_bytes": "provenance_bytes_value", + "intoto_provenance": { + "builder_config": {"id": "id_value"}, + "recipe": { + "type_": "type__value", + "defined_in_material": 1971, + "entry_point": "entry_point_value", + "arguments": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + "environment": {}, + }, + "metadata": { + "build_invocation_id": "build_invocation_id_value", + "build_started_on": {}, + "build_finished_on": {}, + "completeness": { + "arguments": True, + "environment": True, + "materials": True, + }, + "reproducible": True, + }, + "materials": ["materials_value1", "materials_value2"], + }, + "intoto_statement": { + "type_": "type__value", + "subject": [{"name": "name_value", "digest": {}}], + "predicate_type": "predicate_type_value", + "provenance": {}, + "slsa_provenance": { + "builder": {"id": "id_value"}, + "recipe": { + "type_": "type__value", + "defined_in_material": 1971, + "entry_point": "entry_point_value", + "arguments": {}, + "environment": {}, + }, + "metadata": { + "build_invocation_id": "build_invocation_id_value", + "build_started_on": {}, + "build_finished_on": {}, + "completeness": { + "arguments": True, + "environment": True, + "materials": True, + }, + "reproducible": True, + }, + "materials": [{"uri": "uri_value", "digest": {}}], + }, + "slsa_provenance_zero_two": { + "builder": {"id": "id_value"}, + "build_type": "build_type_value", + "invocation": { + "config_source": { + "uri": "uri_value", + "digest": {}, + "entry_point": "entry_point_value", + }, + "parameters": {"fields": {}}, + "environment": {}, + }, + "build_config": {}, + "metadata": { + "build_invocation_id": "build_invocation_id_value", + "build_started_on": {}, + "build_finished_on": {}, + "completeness": { + "parameters": True, + "environment": True, + "materials": True, + }, + "reproducible": True, + }, + "materials": [{"uri": "uri_value", "digest": {}}], + }, + }, + "in_toto_slsa_provenance_v1": { + "type_": "type__value", + "subject": {}, + "predicate_type": "predicate_type_value", + "predicate": { + "build_definition": { + "build_type": "build_type_value", + "external_parameters": {}, + "internal_parameters": {}, + "resolved_dependencies": [ + { + "name": "name_value", + "uri": "uri_value", + "digest": {}, + "content": b"content_blob", + "download_location": "download_location_value", + "media_type": "media_type_value", + "annotations": {}, + } + ], + }, + "run_details": { + "builder": { + "id": "id_value", + "version": {}, + "builder_dependencies": {}, + }, + "metadata": { + "invocation_id": "invocation_id_value", + "started_on": {}, + "finished_on": {}, + }, + "byproducts": {}, + }, + }, + }, + }, + "image": { + "fingerprint": { + "v1_name": "v1_name_value", + "v2_blob": ["v2_blob_value1", "v2_blob_value2"], + "v2_name": "v2_name_value", + }, + "distance": 843, + "layer_info": [ + {"directive": "directive_value", "arguments": "arguments_value"} + ], + "base_resource_url": "base_resource_url_value", + }, + "package": { + "name": "name_value", + "location": [ + {"cpe_uri": "cpe_uri_value", "version": {}, "path": "path_value"} + ], + "package_type": "package_type_value", + "cpe_uri": "cpe_uri_value", + "architecture": 1, + "license_": { + "expression": "expression_value", + "comments": "comments_value", + }, + "version": {}, + }, + "deployment": { + "user_email": "user_email_value", + "deploy_time": {}, + "undeploy_time": {}, + "config": "config_value", + "address": "address_value", + "resource_uri": ["resource_uri_value1", "resource_uri_value2"], + "platform": 1, + }, + "discovery": { + "continuous_analysis": 1, + "analysis_status": 1, + "analysis_completed": { + "analysis_type": ["analysis_type_value1", "analysis_type_value2"] + }, + "analysis_error": [ + {"code": 411, "message": "message_value", "details": {}} + ], + "analysis_status_error": {}, + "cpe": "cpe_value", + "last_scan_time": {}, + "archive_time": {}, + "sbom_status": {"sbom_state": 1, "error": "error_value"}, + "vulnerability_attestation": { + "last_attempt_time": {}, + "state": 1, + "error": "error_value", + }, + }, + "attestation": { + "serialized_payload": b"serialized_payload_blob", + "signatures": [ + {"signature": b"signature_blob", "public_key_id": "public_key_id_value"} + ], + "jwts": [{"compact_jwt": "compact_jwt_value"}], + }, + "upgrade": { + "package": "package_value", + "parsed_version": {}, + "distribution": { + "cpe_uri": "cpe_uri_value", + "classification": "classification_value", + "severity": "severity_value", + "cve": ["cve_value1", "cve_value2"], + }, + "windows_update": { + "identity": {"update_id": "update_id_value", "revision": 879}, + "title": "title_value", + "description": "description_value", + "categories": [ + {"category_id": "category_id_value", "name": "name_value"} + ], + "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], + "support_url": "support_url_value", + "last_published_timestamp": {}, + }, + }, + "compliance": { + "non_compliant_files": [ + { + "path": "path_value", + "display_command": "display_command_value", + "reason": "reason_value", + } + ], + "non_compliance_reason": "non_compliance_reason_value", + "version": { + "cpe_uri": "cpe_uri_value", + "benchmark_document": "benchmark_document_value", + "version": "version_value", + }, + }, + "dsse_attestation": { + "envelope": { + "payload": b"payload_blob", + "payload_type": "payload_type_value", + "signatures": [{"sig": b"sig_blob", "keyid": "keyid_value"}], + }, + "statement": {}, + }, + "sbom_reference": { + "payload": { + "type_": "type__value", + "predicate_type": "predicate_type_value", + "subject": {}, + "predicate": { + "referrer_id": "referrer_id_value", + "location": "location_value", + "mime_type": "mime_type_value", + "digest": {}, + }, + }, + "payload_type": "payload_type_value", + "signatures": {}, + }, + "secret": { + "kind": 1, + "locations": [{"file_location": {}}], + "statuses": [{"status": 1, "update_time": {}, "message": "message_value"}], + }, + "envelope": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = grafeas.UpdateOccurrenceRequest.meta.fields["occurrence"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["occurrence"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["occurrence"][field])): + del request_init["occurrence"][field][i][subfield] + else: + del request_init["occurrence"][field][subfield] + 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 = grafeas.Occurrence( + name="name_value", + resource_uri="resource_uri_value", + note_name="note_name_value", + kind=common.NoteKind.VULNERABILITY, + remediation="remediation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Occurrence.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Occurrence) + assert response.name == "name_value" + assert response.resource_uri == "resource_uri_value" + assert response.note_name == "note_name_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.remediation == "remediation_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_occurrence_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_update_occurrence" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_update_occurrence_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_update_occurrence" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.UpdateOccurrenceRequest.pb( + grafeas.UpdateOccurrenceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Occurrence.to_json(grafeas.Occurrence()) + req.return_value.content = return_value + + request = grafeas.UpdateOccurrenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Occurrence() + post_with_metadata.return_value = grafeas.Occurrence(), metadata + + client.update_occurrence( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_occurrence_note_rest_bad_request( + request_type=grafeas.GetOccurrenceNoteRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_occurrence_note(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.GetOccurrenceNoteRequest, + dict, + ], +) +def test_get_occurrence_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/occurrences/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 = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_occurrence_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_occurrence_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_get_occurrence_note" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_get_occurrence_note_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_get_occurrence_note" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.GetOccurrenceNoteRequest.pb( + grafeas.GetOccurrenceNoteRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.GetOccurrenceNoteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + post_with_metadata.return_value = grafeas.Note(), metadata + + client.get_occurrence_note( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_note_rest_bad_request(request_type=grafeas.GetNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_note(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.GetNoteRequest, + dict, + ], +) +def test_get_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_get_note" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_get_note_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_get_note" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.GetNoteRequest.pb(grafeas.GetNoteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.GetNoteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + post_with_metadata.return_value = grafeas.Note(), metadata + + client.get_note( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_notes_rest_bad_request(request_type=grafeas.ListNotesRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_notes(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.ListNotesRequest, + dict, + ], +) +def test_list_notes_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = grafeas.ListNotesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.ListNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_notes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notes_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_list_notes" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_list_notes_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_list_notes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.ListNotesRequest.pb(grafeas.ListNotesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.ListNotesResponse.to_json(grafeas.ListNotesResponse()) + req.return_value.content = return_value + + request = grafeas.ListNotesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.ListNotesResponse() + post_with_metadata.return_value = grafeas.ListNotesResponse(), metadata + + client.list_notes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_note_rest_bad_request(request_type=grafeas.DeleteNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_note(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.DeleteNoteRequest, + dict, + ], +) +def test_delete_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_note(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "pre_delete_note" + ) as pre: + pre.assert_not_called() + pb_message = grafeas.DeleteNoteRequest.pb(grafeas.DeleteNoteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = grafeas.DeleteNoteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_note( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_note_rest_bad_request(request_type=grafeas.CreateNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_note(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.CreateNoteRequest, + dict, + ], +) +def test_create_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["note"] = { + "name": "name_value", + "short_description": "short_description_value", + "long_description": "long_description_value", + "kind": 1, + "related_url": [{"url": "url_value", "label": "label_value"}], + "expiration_time": {"seconds": 751, "nanos": 543}, + "create_time": {}, + "update_time": {}, + "related_note_names": [ + "related_note_names_value1", + "related_note_names_value2", + ], + "vulnerability": { + "cvss_score": 0.1082, + "severity": 1, + "details": [ + { + "severity_name": "severity_name_value", + "description": "description_value", + "package_type": "package_type_value", + "affected_cpe_uri": "affected_cpe_uri_value", + "affected_package": "affected_package_value", + "affected_version_start": { + "epoch": 527, + "name": "name_value", + "revision": "revision_value", + "inclusive": True, + "kind": 1, + "full_name": "full_name_value", + }, + "affected_version_end": {}, + "fixed_cpe_uri": "fixed_cpe_uri_value", + "fixed_package": "fixed_package_value", + "fixed_version": {}, + "is_obsolete": True, + "source_update_time": {}, + "source": "source_value", + "vendor": "vendor_value", + } + ], + "cvss_v3": { + "base_score": 0.1046, + "exploitability_score": 0.21580000000000002, + "impact_score": 0.1273, + "attack_vector": 1, + "attack_complexity": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + "windows_details": [ + { + "cpe_uri": "cpe_uri_value", + "name": "name_value", + "description": "description_value", + "fixing_kbs": [{"name": "name_value", "url": "url_value"}], + } + ], + "source_update_time": {}, + "cvss_version": 1, + "cvss_v2": { + "base_score": 0.1046, + "exploitability_score": 0.21580000000000002, + "impact_score": 0.1273, + "attack_vector": 1, + "attack_complexity": 1, + "authentication": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + }, + "build": {"builder_version": "builder_version_value"}, + "image": { + "resource_url": "resource_url_value", + "fingerprint": { + "v1_name": "v1_name_value", + "v2_blob": ["v2_blob_value1", "v2_blob_value2"], + "v2_name": "v2_name_value", + }, + }, + "package": { + "name": "name_value", + "distribution": [ + { + "cpe_uri": "cpe_uri_value", + "architecture": 1, + "latest_version": {}, + "maintainer": "maintainer_value", + "url": "url_value", + "description": "description_value", + } + ], + "package_type": "package_type_value", + "cpe_uri": "cpe_uri_value", + "architecture": 1, + "version": {}, + "maintainer": "maintainer_value", + "url": "url_value", + "description": "description_value", + "license_": { + "expression": "expression_value", + "comments": "comments_value", + }, + "digest": [{"algo": "algo_value", "digest_bytes": b"digest_bytes_blob"}], + }, + "deployment": {"resource_uri": ["resource_uri_value1", "resource_uri_value2"]}, + "discovery": {"analysis_kind": 1}, + "attestation": {"hint": {"human_readable_name": "human_readable_name_value"}}, + "upgrade": { + "package": "package_value", + "version": {}, + "distributions": [ + { + "cpe_uri": "cpe_uri_value", + "classification": "classification_value", + "severity": "severity_value", + "cve": ["cve_value1", "cve_value2"], + } + ], + "windows_update": { + "identity": {"update_id": "update_id_value", "revision": 879}, + "title": "title_value", + "description": "description_value", + "categories": [ + {"category_id": "category_id_value", "name": "name_value"} + ], + "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], + "support_url": "support_url_value", + "last_published_timestamp": {}, + }, + }, + "compliance": { + "title": "title_value", + "description": "description_value", + "version": [ + { + "cpe_uri": "cpe_uri_value", + "benchmark_document": "benchmark_document_value", + "version": "version_value", + } + ], + "rationale": "rationale_value", + "remediation": "remediation_value", + "cis_benchmark": {"profile_level": 1384, "severity": 1}, + "scan_instructions": b"scan_instructions_blob", + "impact": "impact_value", + }, + "dsse_attestation": { + "hint": {"human_readable_name": "human_readable_name_value"} + }, + "vulnerability_assessment": { + "title": "title_value", + "short_description": "short_description_value", + "long_description": "long_description_value", + "language_code": "language_code_value", + "publisher": { + "name": "name_value", + "issuing_authority": "issuing_authority_value", + "publisher_namespace": "publisher_namespace_value", + }, + "product": { + "name": "name_value", + "id": "id_value", + "generic_uri": "generic_uri_value", + }, + "assessment": { + "cve": "cve_value", + "vulnerability_id": "vulnerability_id_value", + "short_description": "short_description_value", + "long_description": "long_description_value", + "related_uris": {}, + "state": 1, + "impacts": ["impacts_value1", "impacts_value2"], + "justification": {"justification_type": 1, "details": "details_value"}, + "remediations": [ + { + "remediation_type": 1, + "details": "details_value", + "remediation_uri": {}, + } + ], + }, + }, + "sbom_reference": {"format_": "format__value", "version": "version_value"}, + "secret": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = grafeas.CreateNoteRequest.meta.fields["note"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["note"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["note"][field])): + del request_init["note"][field][i][subfield] + else: + del request_init["note"][field][subfield] + 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 = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_create_note" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_create_note_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_create_note" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.CreateNoteRequest.pb(grafeas.CreateNoteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.CreateNoteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + post_with_metadata.return_value = grafeas.Note(), metadata + + client.create_note( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_create_notes_rest_bad_request( + request_type=grafeas.BatchCreateNotesRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_create_notes(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.BatchCreateNotesRequest, + dict, + ], +) +def test_batch_create_notes_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = grafeas.BatchCreateNotesResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.BatchCreateNotesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_notes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.BatchCreateNotesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_notes_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_batch_create_notes" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_batch_create_notes_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_batch_create_notes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.BatchCreateNotesRequest.pb( + grafeas.BatchCreateNotesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.BatchCreateNotesResponse.to_json( + grafeas.BatchCreateNotesResponse() + ) + req.return_value.content = return_value + + request = grafeas.BatchCreateNotesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.BatchCreateNotesResponse() + post_with_metadata.return_value = grafeas.BatchCreateNotesResponse(), metadata + + client.batch_create_notes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_note_rest_bad_request(request_type=grafeas.UpdateNoteRequest): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_note(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.UpdateNoteRequest, + dict, + ], +) +def test_update_note_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/sample2"} + request_init["note"] = { + "name": "name_value", + "short_description": "short_description_value", + "long_description": "long_description_value", + "kind": 1, + "related_url": [{"url": "url_value", "label": "label_value"}], + "expiration_time": {"seconds": 751, "nanos": 543}, + "create_time": {}, + "update_time": {}, + "related_note_names": [ + "related_note_names_value1", + "related_note_names_value2", + ], + "vulnerability": { + "cvss_score": 0.1082, + "severity": 1, + "details": [ + { + "severity_name": "severity_name_value", + "description": "description_value", + "package_type": "package_type_value", + "affected_cpe_uri": "affected_cpe_uri_value", + "affected_package": "affected_package_value", + "affected_version_start": { + "epoch": 527, + "name": "name_value", + "revision": "revision_value", + "inclusive": True, + "kind": 1, + "full_name": "full_name_value", + }, + "affected_version_end": {}, + "fixed_cpe_uri": "fixed_cpe_uri_value", + "fixed_package": "fixed_package_value", + "fixed_version": {}, + "is_obsolete": True, + "source_update_time": {}, + "source": "source_value", + "vendor": "vendor_value", + } + ], + "cvss_v3": { + "base_score": 0.1046, + "exploitability_score": 0.21580000000000002, + "impact_score": 0.1273, + "attack_vector": 1, + "attack_complexity": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + "windows_details": [ + { + "cpe_uri": "cpe_uri_value", + "name": "name_value", + "description": "description_value", + "fixing_kbs": [{"name": "name_value", "url": "url_value"}], + } + ], + "source_update_time": {}, + "cvss_version": 1, + "cvss_v2": { + "base_score": 0.1046, + "exploitability_score": 0.21580000000000002, + "impact_score": 0.1273, + "attack_vector": 1, + "attack_complexity": 1, + "authentication": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + }, + "build": {"builder_version": "builder_version_value"}, + "image": { + "resource_url": "resource_url_value", + "fingerprint": { + "v1_name": "v1_name_value", + "v2_blob": ["v2_blob_value1", "v2_blob_value2"], + "v2_name": "v2_name_value", + }, + }, + "package": { + "name": "name_value", + "distribution": [ + { + "cpe_uri": "cpe_uri_value", + "architecture": 1, + "latest_version": {}, + "maintainer": "maintainer_value", + "url": "url_value", + "description": "description_value", + } + ], + "package_type": "package_type_value", + "cpe_uri": "cpe_uri_value", + "architecture": 1, + "version": {}, + "maintainer": "maintainer_value", + "url": "url_value", + "description": "description_value", + "license_": { + "expression": "expression_value", + "comments": "comments_value", + }, + "digest": [{"algo": "algo_value", "digest_bytes": b"digest_bytes_blob"}], + }, + "deployment": {"resource_uri": ["resource_uri_value1", "resource_uri_value2"]}, + "discovery": {"analysis_kind": 1}, + "attestation": {"hint": {"human_readable_name": "human_readable_name_value"}}, + "upgrade": { + "package": "package_value", + "version": {}, + "distributions": [ + { + "cpe_uri": "cpe_uri_value", + "classification": "classification_value", + "severity": "severity_value", + "cve": ["cve_value1", "cve_value2"], + } + ], + "windows_update": { + "identity": {"update_id": "update_id_value", "revision": 879}, + "title": "title_value", + "description": "description_value", + "categories": [ + {"category_id": "category_id_value", "name": "name_value"} + ], + "kb_article_ids": ["kb_article_ids_value1", "kb_article_ids_value2"], + "support_url": "support_url_value", + "last_published_timestamp": {}, + }, + }, + "compliance": { + "title": "title_value", + "description": "description_value", + "version": [ + { + "cpe_uri": "cpe_uri_value", + "benchmark_document": "benchmark_document_value", + "version": "version_value", + } + ], + "rationale": "rationale_value", + "remediation": "remediation_value", + "cis_benchmark": {"profile_level": 1384, "severity": 1}, + "scan_instructions": b"scan_instructions_blob", + "impact": "impact_value", + }, + "dsse_attestation": { + "hint": {"human_readable_name": "human_readable_name_value"} + }, + "vulnerability_assessment": { + "title": "title_value", + "short_description": "short_description_value", + "long_description": "long_description_value", + "language_code": "language_code_value", + "publisher": { + "name": "name_value", + "issuing_authority": "issuing_authority_value", + "publisher_namespace": "publisher_namespace_value", + }, + "product": { + "name": "name_value", + "id": "id_value", + "generic_uri": "generic_uri_value", + }, + "assessment": { + "cve": "cve_value", + "vulnerability_id": "vulnerability_id_value", + "short_description": "short_description_value", + "long_description": "long_description_value", + "related_uris": {}, + "state": 1, + "impacts": ["impacts_value1", "impacts_value2"], + "justification": {"justification_type": 1, "details": "details_value"}, + "remediations": [ + { + "remediation_type": 1, + "details": "details_value", + "remediation_uri": {}, + } + ], + }, + }, + "sbom_reference": {"format_": "format__value", "version": "version_value"}, + "secret": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = grafeas.UpdateNoteRequest.meta.fields["note"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["note"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["note"][field])): + del request_init["note"][field][i][subfield] + else: + del request_init["note"][field][subfield] + 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 = grafeas.Note( + name="name_value", + short_description="short_description_value", + long_description="long_description_value", + kind=common.NoteKind.VULNERABILITY, + related_note_names=["related_note_names_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.Note.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_note(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, grafeas.Note) + assert response.name == "name_value" + assert response.short_description == "short_description_value" + assert response.long_description == "long_description_value" + assert response.kind == common.NoteKind.VULNERABILITY + assert response.related_note_names == ["related_note_names_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_note_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_update_note" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_update_note_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_update_note" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.UpdateNoteRequest.pb(grafeas.UpdateNoteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.Note.to_json(grafeas.Note()) + req.return_value.content = return_value + + request = grafeas.UpdateNoteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.Note() + post_with_metadata.return_value = grafeas.Note(), metadata + + client.update_note( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_note_occurrences_rest_bad_request( + request_type=grafeas.ListNoteOccurrencesRequest, +): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_note_occurrences(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grafeas.ListNoteOccurrencesRequest, + dict, + ], +) +def test_list_note_occurrences_rest_call_success(request_type): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/notes/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 = grafeas.ListNoteOccurrencesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = grafeas.ListNoteOccurrencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_note_occurrences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNoteOccurrencesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_note_occurrences_rest_interceptors(null_interceptor): + transport = transports.GrafeasRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GrafeasRestInterceptor(), + ) + client = GrafeasClient(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.GrafeasRestInterceptor, "post_list_note_occurrences" + ) as post, mock.patch.object( + transports.GrafeasRestInterceptor, "post_list_note_occurrences_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GrafeasRestInterceptor, "pre_list_note_occurrences" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = grafeas.ListNoteOccurrencesRequest.pb( + grafeas.ListNoteOccurrencesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = grafeas.ListNoteOccurrencesResponse.to_json( + grafeas.ListNoteOccurrencesResponse() + ) + req.return_value.content = return_value + + request = grafeas.ListNoteOccurrencesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = grafeas.ListNoteOccurrencesResponse() + post_with_metadata.return_value = ( + grafeas.ListNoteOccurrencesResponse(), + metadata, + ) + + client.list_note_occurrences( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_occurrence), "__call__") as call: + client.get_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_occurrences_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_occurrences), "__call__") as call: + client.list_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListOccurrencesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_occurrence), "__call__" + ) as call: + client.delete_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_occurrence), "__call__" + ) as call: + client.create_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_occurrences_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_occurrences), "__call__" + ) as call: + client.batch_create_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateOccurrencesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_occurrence_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_occurrence), "__call__" + ) as call: + client.update_occurrence(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateOccurrenceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_occurrence_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_occurrence_note), "__call__" + ) as call: + client.get_occurrence_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetOccurrenceNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_note), "__call__") as call: + client.get_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.GetNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_notes_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_notes), "__call__") as call: + client.list_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNotesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_note), "__call__") as call: + client.delete_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.DeleteNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_note), "__call__") as call: + client.create_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.CreateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_notes_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_notes), "__call__" + ) as call: + client.batch_create_notes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.BatchCreateNotesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_note_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_note), "__call__") as call: + client.update_note(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.UpdateNoteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_note_occurrences_empty_call_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_note_occurrences), "__call__" + ) as call: + client.list_note_occurrences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grafeas.ListNoteOccurrencesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GrafeasGrpcTransport, + ) + + +def test_grafeas_base_transport(): + # Instantiate the base transport. + with mock.patch( + "grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GrafeasTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_occurrence", + "list_occurrences", + "delete_occurrence", + "create_occurrence", + "batch_create_occurrences", + "update_occurrence", + "get_occurrence_note", + "get_note", + "list_notes", + "delete_note", + "create_note", + "batch_create_notes", + "update_note", + "list_note_occurrences", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_grafeas_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( + "grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=(), + quota_project_id="octopus", + ) + + +def test_grafeas_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( + "grafeas.grafeas_v1.services.grafeas.transports.GrafeasTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GrafeasTransport() + adc.assert_called_once() + + +def test_grafeas_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) + GrafeasClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=(), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + ], +) +def test_grafeas_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=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GrafeasGrpcTransport, + transports.GrafeasGrpcAsyncIOTransport, + transports.GrafeasRestTransport, + ], +) +def test_grafeas_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.GrafeasGrpcTransport, grpc_helpers), + (transports.GrafeasGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_grafeas_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( + ":443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=(), + scopes=["1", "2"], + default_host="", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport], +) +def test_grafeas_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_grafeas_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.GrafeasRestTransport( + 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_grafeas_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GrafeasGrpcTransport( + 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_grafeas_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GrafeasGrpcAsyncIOTransport( + 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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport], +) +def test_grafeas_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.GrafeasGrpcTransport, transports.GrafeasGrpcAsyncIOTransport], +) +def test_grafeas_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_note_path(): + project = "squid" + note = "clam" + expected = "projects/{project}/notes/{note}".format( + project=project, + note=note, + ) + actual = GrafeasClient.note_path(project, note) + assert expected == actual + + +def test_parse_note_path(): + expected = { + "project": "whelk", + "note": "octopus", + } + path = GrafeasClient.note_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_note_path(path) + assert expected == actual + + +def test_occurrence_path(): + project = "oyster" + occurrence = "nudibranch" + expected = "projects/{project}/occurrences/{occurrence}".format( + project=project, + occurrence=occurrence, + ) + actual = GrafeasClient.occurrence_path(project, occurrence) + assert expected == actual + + +def test_parse_occurrence_path(): + expected = { + "project": "cuttlefish", + "occurrence": "mussel", + } + path = GrafeasClient.occurrence_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_occurrence_path(path) + assert expected == actual + + +def test_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = GrafeasClient.project_path(project) + assert expected == actual + + +def test_parse_project_path(): + expected = { + "project": "nautilus", + } + path = GrafeasClient.project_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_project_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = GrafeasClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = GrafeasClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = GrafeasClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = GrafeasClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = GrafeasClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = GrafeasClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = GrafeasClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = GrafeasClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = GrafeasClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = GrafeasClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GrafeasClient.parse_common_location_path(path) + assert expected == actual + + +def test_transport_close_grpc(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = GrafeasAsyncClient( + credentials=async_anonymous_credentials(), 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_transport_close_rest(): + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = GrafeasClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called()