diff --git a/devtools-containeranalysis-v1-py.tar.gz b/devtools-containeranalysis-v1-py.tar.gz new file mode 100644 index 0000000..e69de29 diff --git a/docs/containeranalysis_v1/types.rst b/docs/containeranalysis_v1/types.rst index b779ea6..c0d2aa5 100644 --- a/docs/containeranalysis_v1/types.rst +++ b/docs/containeranalysis_v1/types.rst @@ -3,3 +3,4 @@ Types for Google Cloud Devtools Containeranalysis v1 API .. automodule:: google.cloud.devtools.containeranalysis_v1.types :members: + :show-inheritance: diff --git a/google/cloud/devtools/containeranalysis/__init__.py b/google/cloud/devtools/containeranalysis/__init__.py index fb5a9de..b86315f 100644 --- a/google/cloud/devtools/containeranalysis/__init__.py +++ b/google/cloud/devtools/containeranalysis/__init__.py @@ -21,8 +21,16 @@ from google.cloud.devtools.containeranalysis_v1.services.container_analysis.client import ( ContainerAnalysisClient, ) +from google.cloud.devtools.containeranalysis_v1.types.containeranalysis import ( + GetVulnerabilityOccurrencesSummaryRequest, +) +from google.cloud.devtools.containeranalysis_v1.types.containeranalysis import ( + VulnerabilityOccurrencesSummary, +) __all__ = ( "ContainerAnalysisAsyncClient", "ContainerAnalysisClient", + "GetVulnerabilityOccurrencesSummaryRequest", + "VulnerabilityOccurrencesSummary", ) diff --git a/google/cloud/devtools/containeranalysis_v1/__init__.py b/google/cloud/devtools/containeranalysis_v1/__init__.py index 66e394e..c5ddb67 100644 --- a/google/cloud/devtools/containeranalysis_v1/__init__.py +++ b/google/cloud/devtools/containeranalysis_v1/__init__.py @@ -16,6 +16,12 @@ # from .services.container_analysis import ContainerAnalysisClient +from .types.containeranalysis import GetVulnerabilityOccurrencesSummaryRequest +from .types.containeranalysis import VulnerabilityOccurrencesSummary -__all__ = ("ContainerAnalysisClient",) +__all__ = ( + "GetVulnerabilityOccurrencesSummaryRequest", + "VulnerabilityOccurrencesSummary", + "ContainerAnalysisClient", +) diff --git a/google/cloud/devtools/containeranalysis_v1/proto/containeranalysis.proto b/google/cloud/devtools/containeranalysis_v1/proto/containeranalysis.proto index 55b842a..f1f1e27 100644 --- a/google/cloud/devtools/containeranalysis_v1/proto/containeranalysis.proto +++ b/google/cloud/devtools/containeranalysis_v1/proto/containeranalysis.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// syntax = "proto3"; @@ -19,9 +18,12 @@ package google.devtools.containeranalysis.v1; import "google/api/annotations.proto"; import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; import "google/iam/v1/iam_policy.proto"; import "google/iam/v1/policy.proto"; import "google/protobuf/timestamp.proto"; +import "grafeas/v1/vulnerability.proto"; option csharp_namespace = "Google.Cloud.DevTools.ContainerAnalysis.V1"; option go_package = "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1;containeranalysis"; @@ -105,4 +107,48 @@ service ContainerAnalysis { }; option (google.api.method_signature) = "resource,permissions"; } + + // Gets a summary of the number and severity of occurrences. + rpc GetVulnerabilityOccurrencesSummary(GetVulnerabilityOccurrencesSummaryRequest) returns (VulnerabilityOccurrencesSummary) { + option (google.api.http) = { + get: "/v1/{parent=projects/*}/occurrences:vulnerabilitySummary" + }; + option (google.api.method_signature) = "parent,filter"; + } +} + +// Request to get a vulnerability summary for some set of occurrences. +message GetVulnerabilityOccurrencesSummaryRequest { + // The name of the project to get a vulnerability summary for in the form of + // `projects/[PROJECT_ID]`. + string parent = 1 [ + (google.api.resource_reference).type = "cloudresourcemanager.googleapis.com/Project", + (google.api.field_behavior) = REQUIRED + ]; + + // The filter expression. + string filter = 2; +} + +// A summary of how many vulnerability occurrences there are per resource and +// severity type. +message VulnerabilityOccurrencesSummary { + // Per resource and severity counts of fixable and total vulnerabilities. + message FixableTotalByDigest { + // The affected resource. + string resource_uri = 1; + + // The severity for this count. SEVERITY_UNSPECIFIED indicates total across + // all severities. + grafeas.v1.Severity severity = 2; + + // The number of fixable vulnerabilities associated with this resource. + int64 fixable_count = 3; + + // The total number of vulnerabilities associated with this resource. + int64 total_count = 4; + } + + // A listing by resource of the number of fixable and total vulnerabilities. + repeated FixableTotalByDigest counts = 1; } diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py index 8365efe..65ed9b8 100644 --- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py +++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py @@ -28,10 +28,11 @@ from google.auth import credentials # type: ignore from google.oauth2 import service_account # type: ignore +from google.cloud.devtools.containeranalysis_v1.types import containeranalysis from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore -from .transports.base import ContainerAnalysisTransport +from .transports.base import ContainerAnalysisTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ContainerAnalysisGrpcAsyncIOTransport from .client import ContainerAnalysisClient @@ -63,9 +64,47 @@ class ContainerAnalysisAsyncClient: DEFAULT_ENDPOINT = ContainerAnalysisClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = ContainerAnalysisClient.DEFAULT_MTLS_ENDPOINT + common_billing_account_path = staticmethod( + ContainerAnalysisClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ContainerAnalysisClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(ContainerAnalysisClient.common_folder_path) + parse_common_folder_path = staticmethod( + ContainerAnalysisClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + ContainerAnalysisClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + ContainerAnalysisClient.parse_common_organization_path + ) + + common_project_path = staticmethod(ContainerAnalysisClient.common_project_path) + parse_common_project_path = staticmethod( + ContainerAnalysisClient.parse_common_project_path + ) + + common_location_path = staticmethod(ContainerAnalysisClient.common_location_path) + parse_common_location_path = staticmethod( + ContainerAnalysisClient.parse_common_location_path + ) + from_service_account_file = ContainerAnalysisClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> ContainerAnalysisTransport: + """Return the transport used by the client instance. + + Returns: + ContainerAnalysisTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(ContainerAnalysisClient).get_transport_class, type(ContainerAnalysisClient) ) @@ -76,6 +115,7 @@ def __init__( credentials: credentials.Credentials = None, transport: Union[str, ContainerAnalysisTransport] = "grpc_asyncio", client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the container analysis client. @@ -91,16 +131,19 @@ def __init__( client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -108,7 +151,10 @@ def __init__( """ self._client = ContainerAnalysisClient( - credentials=credentials, transport=transport, client_options=client_options, + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, ) def get_grafeas_client(self) -> grafeas_v1.GrafeasClient: @@ -230,7 +276,8 @@ async def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -242,20 +289,14 @@ async def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.set_iam_policy, default_timeout=30.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -380,7 +421,8 @@ async def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -392,20 +434,14 @@ async def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_iam_policy, default_timeout=30.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -473,7 +509,8 @@ async def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + 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." @@ -485,29 +522,104 @@ async def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_vulnerability_occurrences_summary( + self, + request: containeranalysis.GetVulnerabilityOccurrencesSummaryRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> containeranalysis.VulnerabilityOccurrencesSummary: + r"""Gets a summary of the number and severity of + occurrences. + + Args: + request (:class:`~.containeranalysis.GetVulnerabilityOccurrencesSummaryRequest`): + The request object. Request to get a vulnerability + summary for some set of occurrences. + parent (:class:`str`): + The name of the project to get a vulnerability summary + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.containeranalysis.VulnerabilityOccurrencesSummary: + A summary of how many vulnerability + occurrences there are per resource and + severity type. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + 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." + ) + + request = containeranalysis.GetVulnerabilityOccurrencesSummaryRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + 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 = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=30.0, - client_info=_client_info, + self._client._transport.get_vulnerability_occurrences_summary, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -518,13 +630,13 @@ async def test_iam_permissions( try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-containeranalysis", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("ContainerAnalysisAsyncClient",) diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py index 67bc8ad..c38a489 100644 --- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py +++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py @@ -16,24 +16,27 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore +from google.cloud.devtools.containeranalysis_v1.types import containeranalysis from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore -from .transports.base import ContainerAnalysisTransport +from .transports.base import ContainerAnalysisTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ContainerAnalysisGrpcTransport from .transports.grpc_asyncio import ContainerAnalysisGrpcAsyncIOTransport @@ -149,12 +152,81 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> ContainerAnalysisTransport: + """Return the transport used by the client instance. + + Returns: + ContainerAnalysisTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, ContainerAnalysisTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ContainerAnalysisTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the container analysis client. @@ -167,48 +239,74 @@ def __init__( transport (Union[str, ~.ContainerAnalysisTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -232,11 +330,11 @@ def __init__( self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, + host=api_endpoint, scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + ssl_channel_credentials=ssl_credentials, quota_project_id=client_options.quota_project_id, + client_info=client_info, ) def get_grafeas_client(self) -> grafeas_v1.GrafeasClient: @@ -371,13 +469,7 @@ def set_iam_policy( request = iam_policy.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -518,13 +610,7 @@ def get_iam_policy( request = iam_policy.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource + request = iam_policy.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -608,25 +694,107 @@ def test_iam_permissions( request = iam_policy.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest() + request = iam_policy.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_vulnerability_occurrences_summary( + self, + request: containeranalysis.GetVulnerabilityOccurrencesSummaryRequest = None, + *, + parent: str = None, + filter: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> containeranalysis.VulnerabilityOccurrencesSummary: + r"""Gets a summary of the number and severity of + occurrences. + + Args: + request (:class:`~.containeranalysis.GetVulnerabilityOccurrencesSummaryRequest`): + The request object. Request to get a vulnerability + summary for some set of occurrences. + parent (:class:`str`): + The name of the project to get a vulnerability summary + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.containeranalysis.VulnerabilityOccurrencesSummary: + A summary of how many vulnerability + occurrences there are per resource and + severity type. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a containeranalysis.GetVulnerabilityOccurrencesSummaryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, containeranalysis.GetVulnerabilityOccurrencesSummaryRequest + ): + request = containeranalysis.GetVulnerabilityOccurrencesSummaryRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) + 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.test_iam_permissions] + rpc = self._transport._wrapped_methods[ + self._transport.get_vulnerability_occurrences_summary + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -637,13 +805,13 @@ def test_iam_permissions( try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-containeranalysis", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("ContainerAnalysisClient",) diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/base.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/base.py index 3e33d8b..1ff3797 100644 --- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/base.py +++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/base.py @@ -19,24 +19,25 @@ import typing import pkg_resources -from google import auth +from google import auth # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore +from google.cloud.devtools.containeranalysis_v1.types import containeranalysis from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-devtools-containeranalysis", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class ContainerAnalysisTransport(abc.ABC): @@ -52,6 +53,7 @@ def __init__( credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. @@ -69,6 +71,11 @@ def __init__( scope (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -96,21 +103,26 @@ def __init__( self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() + self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self): + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, default_timeout=30.0, client_info=_client_info, + self.set_iam_policy, default_timeout=30.0, client_info=client_info, ), self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, default_timeout=30.0, client_info=_client_info, + self.get_iam_policy, default_timeout=30.0, client_info=client_info, ), self.test_iam_permissions: gapic_v1.method.wrap_method( self.test_iam_permissions, default_timeout=30.0, - client_info=_client_info, + client_info=client_info, + ), + self.get_vulnerability_occurrences_summary: gapic_v1.method.wrap_method( + self.get_vulnerability_occurrences_summary, + default_timeout=None, + client_info=client_info, ), } @@ -144,5 +156,17 @@ def test_iam_permissions( ]: raise NotImplementedError() + @property + def get_vulnerability_occurrences_summary( + self, + ) -> typing.Callable[ + [containeranalysis.GetVulnerabilityOccurrencesSummaryRequest], + typing.Union[ + containeranalysis.VulnerabilityOccurrencesSummary, + typing.Awaitable[containeranalysis.VulnerabilityOccurrencesSummary], + ], + ]: + raise NotImplementedError() + __all__ = ("ContainerAnalysisTransport",) diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc.py index dd846b9..ddd59e6 100644 --- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc.py +++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc.py @@ -15,20 +15,22 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore +from google.cloud.devtools.containeranalysis_v1.types import containeranalysis from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore -from .base import ContainerAnalysisTransport +from .base import ContainerAnalysisTransport, DEFAULT_CLIENT_INFO class ContainerAnalysisGrpcTransport(ContainerAnalysisTransport): @@ -70,7 +72,9 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -89,16 +93,23 @@ def __init__( ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + 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 grpc 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're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -106,6 +117,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -113,7 +126,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -144,6 +163,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) self._stubs = {} # type: Dict[str, Callable] @@ -154,6 +191,7 @@ def __init__( credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + client_info=client_info, ) @classmethod @@ -164,7 +202,7 @@ def create_channel( credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, - **kwargs + **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: @@ -198,24 +236,13 @@ def create_channel( credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. return self._grpc_channel @property @@ -321,5 +348,38 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + @property + def get_vulnerability_occurrences_summary( + self, + ) -> Callable[ + [containeranalysis.GetVulnerabilityOccurrencesSummaryRequest], + containeranalysis.VulnerabilityOccurrencesSummary, + ]: + r"""Return a callable for the get vulnerability occurrences + summary method over gRPC. + + Gets a summary of the number and severity of + occurrences. + + Returns: + Callable[[~.GetVulnerabilityOccurrencesSummaryRequest], + ~.VulnerabilityOccurrencesSummary]: + 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_vulnerability_occurrences_summary" not in self._stubs: + self._stubs[ + "get_vulnerability_occurrences_summary" + ] = self.grpc_channel.unary_unary( + "/google.devtools.containeranalysis.v1.ContainerAnalysis/GetVulnerabilityOccurrencesSummary", + request_serializer=containeranalysis.GetVulnerabilityOccurrencesSummaryRequest.serialize, + response_deserializer=containeranalysis.VulnerabilityOccurrencesSummary.deserialize, + ) + return self._stubs["get_vulnerability_occurrences_summary"] + __all__ = ("ContainerAnalysisGrpcTransport",) diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc_asyncio.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc_asyncio.py index 24bad10..af63a0d 100644 --- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc_asyncio.py +++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/transports/grpc_asyncio.py @@ -15,19 +15,23 @@ # limitations under the License. # +import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore +from google.cloud.devtools.containeranalysis_v1.types import containeranalysis from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore -from .base import ContainerAnalysisTransport +from .base import ContainerAnalysisTransport, DEFAULT_CLIENT_INFO from .grpc import ContainerAnalysisGrpcTransport @@ -112,7 +116,9 @@ def __init__( channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -132,16 +138,23 @@ def __init__( are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + 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 grpc 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're developing + your own client library. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -149,6 +162,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -156,13 +171,24 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: @@ -182,6 +208,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) # Run the base constructor. super().__init__( @@ -190,6 +234,7 @@ def __init__( credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + client_info=client_info, ) self._stubs = {} @@ -201,13 +246,6 @@ def grpc_channel(self) -> aio.Channel: This property caches on the instance; repeated calls return the same channel. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - # Return the channel from cache. return self._grpc_channel @@ -315,5 +353,38 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + @property + def get_vulnerability_occurrences_summary( + self, + ) -> Callable[ + [containeranalysis.GetVulnerabilityOccurrencesSummaryRequest], + Awaitable[containeranalysis.VulnerabilityOccurrencesSummary], + ]: + r"""Return a callable for the get vulnerability occurrences + summary method over gRPC. + + Gets a summary of the number and severity of + occurrences. + + Returns: + Callable[[~.GetVulnerabilityOccurrencesSummaryRequest], + Awaitable[~.VulnerabilityOccurrencesSummary]]: + 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_vulnerability_occurrences_summary" not in self._stubs: + self._stubs[ + "get_vulnerability_occurrences_summary" + ] = self.grpc_channel.unary_unary( + "/google.devtools.containeranalysis.v1.ContainerAnalysis/GetVulnerabilityOccurrencesSummary", + request_serializer=containeranalysis.GetVulnerabilityOccurrencesSummaryRequest.serialize, + response_deserializer=containeranalysis.VulnerabilityOccurrencesSummary.deserialize, + ) + return self._stubs["get_vulnerability_occurrences_summary"] + __all__ = ("ContainerAnalysisGrpcAsyncIOTransport",) diff --git a/google/cloud/devtools/containeranalysis_v1/types/__init__.py b/google/cloud/devtools/containeranalysis_v1/types/__init__.py index e1d07d2..4690bc4 100644 --- a/google/cloud/devtools/containeranalysis_v1/types/__init__.py +++ b/google/cloud/devtools/containeranalysis_v1/types/__init__.py @@ -15,5 +15,13 @@ # limitations under the License. # +from .containeranalysis import ( + GetVulnerabilityOccurrencesSummaryRequest, + VulnerabilityOccurrencesSummary, +) -__all__ = () + +__all__ = ( + "GetVulnerabilityOccurrencesSummaryRequest", + "VulnerabilityOccurrencesSummary", +) diff --git a/google/cloud/devtools/containeranalysis_v1/types/containeranalysis.py b/google/cloud/devtools/containeranalysis_v1/types/containeranalysis.py index 0d29807..fa22eaa 100644 --- a/google/cloud/devtools/containeranalysis_v1/types/containeranalysis.py +++ b/google/cloud/devtools/containeranalysis_v1/types/containeranalysis.py @@ -15,10 +15,75 @@ # limitations under the License. # +import proto # type: ignore + + +from grafeas.grafeas_v1.types import vulnerability # type: ignore + __protobuf__ = proto.module( - package="google.devtools.containeranalysis.v1", manifest={}, + package="google.devtools.containeranalysis.v1", + manifest={ + "GetVulnerabilityOccurrencesSummaryRequest", + "VulnerabilityOccurrencesSummary", + }, ) +class GetVulnerabilityOccurrencesSummaryRequest(proto.Message): + r"""Request to get a vulnerability summary for some set of + occurrences. + + Attributes: + parent (str): + The name of the project to get a vulnerability summary for + in the form of ``projects/[PROJECT_ID]``. + filter (str): + The filter expression. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + +class VulnerabilityOccurrencesSummary(proto.Message): + r"""A summary of how many vulnerability occurrences there are per + resource and severity type. + + Attributes: + counts (Sequence[~.containeranalysis.VulnerabilityOccurrencesSummary.FixableTotalByDigest]): + A listing by resource of the number of + fixable and total vulnerabilities. + """ + + class FixableTotalByDigest(proto.Message): + r"""Per resource and severity counts of fixable and total + vulnerabilities. + + Attributes: + resource_uri (str): + The affected resource. + severity (~.vulnerability.Severity): + The severity for this count. SEVERITY_UNSPECIFIED indicates + total across all severities. + fixable_count (int): + The number of fixable vulnerabilities + associated with this resource. + total_count (int): + The total number of vulnerabilities + associated with this resource. + """ + + resource_uri = proto.Field(proto.STRING, number=1) + + severity = proto.Field(proto.ENUM, number=2, enum=vulnerability.Severity,) + + fixable_count = proto.Field(proto.INT64, number=3) + + total_count = proto.Field(proto.INT64, number=4) + + counts = proto.RepeatedField(proto.MESSAGE, number=1, message=FixableTotalByDigest,) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_containeranalysis_v1_keywords.py b/scripts/fixup_containeranalysis_v1_keywords.py index 5129740..f5bb70f 100644 --- a/scripts/fixup_containeranalysis_v1_keywords.py +++ b/scripts/fixup_containeranalysis_v1_keywords.py @@ -1,3 +1,4 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC @@ -41,6 +42,7 @@ class containeranalysisCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'get_iam_policy': ('resource', 'options', ), + 'get_vulnerability_occurrences_summary': ('parent', 'filter', ), 'set_iam_policy': ('resource', 'policy', ), 'test_iam_permissions': ('resource', 'permissions', ), diff --git a/setup.py b/setup.py index c4f727a..8ccf816 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ version = "2.0.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.21.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "proto-plus >= 1.4.0", "libcst >= 0.2.5", diff --git a/synth.metadata b/synth.metadata index 0b993b2..bdda4e4 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-containeranalysis.git", - "sha": "2ce48dca5bf1ca50f30266dd0b2deb5e36346c6c" + "remote": "git@github.com:googleapis/python-containeranalysis", + "sha": "96b248426373bd235b54219a499275fdbbf945d8" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "43a62a87b70010d9cf9be31e99ea230a535e1b47", - "internalRef": "326109811" + "sha": "754a312a0d01cfc1484d397872ff45e5565af0da", + "internalRef": "342758098" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "e89175cf074dccc4babb4eca66ae913696e47a71" + "sha": "d5fc0bcf9ea9789c5b0e3154a9e3b29e5cea6116" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "e89175cf074dccc4babb4eca66ae913696e47a71" + "sha": "d5fc0bcf9ea9789c5b0e3154a9e3b29e5cea6116" } } ], diff --git a/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py b/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py index 8edd78f..a8f1156 100644 --- a/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py +++ b/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py @@ -27,6 +27,7 @@ from google import auth from google.api_core import client_options from google.api_core import exceptions +from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.auth import credentials @@ -40,6 +41,7 @@ from google.cloud.devtools.containeranalysis_v1.services.container_analysis import ( transports, ) +from google.cloud.devtools.containeranalysis_v1.types import containeranalysis from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore from google.iam.v1 import options_pb2 as options # type: ignore from google.iam.v1 import policy_pb2 as policy # type: ignore @@ -102,12 +104,12 @@ def test_container_analysis_client_from_service_account_file(client_class): ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds client = client_class.from_service_account_json("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds - assert client._transport._host == "containeranalysis.googleapis.com:443" + assert client.transport._host == "containeranalysis.googleapis.com:443" def test_container_analysis_client_get_transport_class(): @@ -163,14 +165,14 @@ def test_container_analysis_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -179,14 +181,14 @@ def test_container_analysis_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -195,90 +197,185 @@ def test_container_analysis_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + ContainerAnalysisClient, + transports.ContainerAnalysisGrpcTransport, + "grpc", + "true", + ), + ( + ContainerAnalysisAsyncClient, + transports.ContainerAnalysisGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + ContainerAnalysisClient, + transports.ContainerAnalysisGrpcTransport, + "grpc", + "false", + ), + ( + ContainerAnalysisAsyncClient, + transports.ContainerAnalysisGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ContainerAnalysisClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ContainerAnalysisClient), +) +@mock.patch.object( + ContainerAnalysisAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ContainerAnalysisAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_container_analysis_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - quota_project_id=None, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): - with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds ): patched.return_value = None - client = client_class() + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, + host=expected_host, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=expected_ssl_channel_creds, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None ): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id="octopus", - ) + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) @pytest.mark.parametrize( @@ -305,9 +402,9 @@ def test_container_analysis_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -335,9 +432,9 @@ def test_container_analysis_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -354,9 +451,9 @@ def test_container_analysis_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -372,7 +469,7 @@ def test_set_iam_policy( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy(version=774, etag=b"etag_blob",) @@ -385,6 +482,7 @@ def test_set_iam_policy( assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -397,19 +495,19 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest +): client = ContainerAnalysisAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.SetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( policy.Policy(version=774, etag=b"etag_blob",) @@ -421,7 +519,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.SetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -431,6 +529,11 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + def test_set_iam_policy_field_headers(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) @@ -440,7 +543,7 @@ def test_set_iam_policy_field_headers(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.set_iam_policy(request) @@ -467,9 +570,7 @@ async def test_set_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.set_iam_policy(request) @@ -484,10 +585,10 @@ async def test_set_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_set_iam_policy_from_dict(): +def test_set_iam_policy_from_dict_foreign(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -504,7 +605,7 @@ def test_set_iam_policy_flattened(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -538,9 +639,7 @@ async def test_set_iam_policy_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -583,7 +682,7 @@ def test_get_iam_policy( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy(version=774, etag=b"etag_blob",) @@ -596,6 +695,7 @@ def test_get_iam_policy( assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) assert response.version == 774 @@ -608,19 +708,19 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest +): client = ContainerAnalysisAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.GetIamPolicyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( policy.Policy(version=774, etag=b"etag_blob",) @@ -632,7 +732,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.GetIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, policy.Policy) @@ -642,6 +742,11 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + def test_get_iam_policy_field_headers(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) @@ -651,7 +756,7 @@ def test_get_iam_policy_field_headers(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.get_iam_policy(request) @@ -678,9 +783,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.get_iam_policy(request) @@ -695,10 +798,10 @@ async def test_get_iam_policy_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_get_iam_policy_from_dict(): +def test_get_iam_policy_from_dict_foreign(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -715,7 +818,7 @@ def test_get_iam_policy_flattened(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -749,9 +852,7 @@ async def test_get_iam_policy_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -795,7 +896,7 @@ def test_test_iam_permissions( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse( @@ -811,6 +912,7 @@ def test_test_iam_permissions( assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -821,18 +923,20 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest +): client = ContainerAnalysisAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.TestIamPermissionsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -845,7 +949,7 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == iam_policy.TestIamPermissionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, iam_policy.TestIamPermissionsResponse) @@ -853,6 +957,11 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): assert response.permissions == ["permissions_value"] +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + def test_test_iam_permissions_field_headers(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) @@ -863,7 +972,7 @@ def test_test_iam_permissions_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = iam_policy.TestIamPermissionsResponse() @@ -892,7 +1001,7 @@ async def test_test_iam_permissions_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( iam_policy.TestIamPermissionsResponse() @@ -910,11 +1019,11 @@ async def test_test_iam_permissions_field_headers_async(): assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -def test_test_iam_permissions_from_dict(): +def test_test_iam_permissions_from_dict_foreign(): client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -933,7 +1042,7 @@ def test_test_iam_permissions_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -975,7 +1084,7 @@ async def test_test_iam_permissions_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -1015,6 +1124,225 @@ async def test_test_iam_permissions_flattened_error_async(): ) +def test_get_vulnerability_occurrences_summary( + transport: str = "grpc", + request_type=containeranalysis.GetVulnerabilityOccurrencesSummaryRequest, +): + client = ContainerAnalysisClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_occurrences_summary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = containeranalysis.VulnerabilityOccurrencesSummary() + + response = client.get_vulnerability_occurrences_summary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == containeranalysis.GetVulnerabilityOccurrencesSummaryRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, containeranalysis.VulnerabilityOccurrencesSummary) + + +def test_get_vulnerability_occurrences_summary_from_dict(): + test_get_vulnerability_occurrences_summary(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_vulnerability_occurrences_summary_async( + transport: str = "grpc_asyncio", + request_type=containeranalysis.GetVulnerabilityOccurrencesSummaryRequest, +): + client = ContainerAnalysisAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_occurrences_summary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + containeranalysis.VulnerabilityOccurrencesSummary() + ) + + response = await client.get_vulnerability_occurrences_summary(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == containeranalysis.GetVulnerabilityOccurrencesSummaryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, containeranalysis.VulnerabilityOccurrencesSummary) + + +@pytest.mark.asyncio +async def test_get_vulnerability_occurrences_summary_async_from_dict(): + await test_get_vulnerability_occurrences_summary_async(request_type=dict) + + +def test_get_vulnerability_occurrences_summary_field_headers(): + client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = containeranalysis.GetVulnerabilityOccurrencesSummaryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_occurrences_summary), "__call__" + ) as call: + call.return_value = containeranalysis.VulnerabilityOccurrencesSummary() + + client.get_vulnerability_occurrences_summary(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_get_vulnerability_occurrences_summary_field_headers_async(): + client = ContainerAnalysisAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = containeranalysis.GetVulnerabilityOccurrencesSummaryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_occurrences_summary), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + containeranalysis.VulnerabilityOccurrencesSummary() + ) + + await client.get_vulnerability_occurrences_summary(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_get_vulnerability_occurrences_summary_flattened(): + client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_occurrences_summary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = containeranalysis.VulnerabilityOccurrencesSummary() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_vulnerability_occurrences_summary( + 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] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +def test_get_vulnerability_occurrences_summary_flattened_error(): + client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_vulnerability_occurrences_summary( + containeranalysis.GetVulnerabilityOccurrencesSummaryRequest(), + parent="parent_value", + filter="filter_value", + ) + + +@pytest.mark.asyncio +async def test_get_vulnerability_occurrences_summary_flattened_async(): + client = ContainerAnalysisAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_occurrences_summary), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = containeranalysis.VulnerabilityOccurrencesSummary() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + containeranalysis.VulnerabilityOccurrencesSummary() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_vulnerability_occurrences_summary( + 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] + + assert args[0].parent == "parent_value" + + assert args[0].filter == "filter_value" + + +@pytest.mark.asyncio +async def test_get_vulnerability_occurrences_summary_flattened_error_async(): + client = ContainerAnalysisAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_vulnerability_occurrences_summary( + containeranalysis.GetVulnerabilityOccurrencesSummaryRequest(), + parent="parent_value", + filter="filter_value", + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ContainerAnalysisGrpcTransport( @@ -1051,7 +1379,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = ContainerAnalysisClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -1069,10 +1397,25 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContainerAnalysisGrpcTransport, + transports.ContainerAnalysisGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ContainerAnalysisClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.ContainerAnalysisGrpcTransport,) + assert isinstance(client.transport, transports.ContainerAnalysisGrpcTransport,) def test_container_analysis_base_transport_error(): @@ -1100,6 +1443,7 @@ def test_container_analysis_base_transport(): "set_iam_policy", "get_iam_policy", "test_iam_permissions", + "get_vulnerability_occurrences_summary", ) for method in methods: with pytest.raises(NotImplementedError): @@ -1125,6 +1469,17 @@ def test_container_analysis_base_transport_with_credentials_file(): ) +def test_container_analysis_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.devtools.containeranalysis_v1.services.container_analysis.transports.ContainerAnalysisTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ContainerAnalysisTransport() + adc.assert_called_once() + + def test_container_analysis_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -1157,7 +1512,7 @@ def test_container_analysis_host_no_port(): api_endpoint="containeranalysis.googleapis.com" ), ) - assert client._transport._host == "containeranalysis.googleapis.com:443" + assert client.transport._host == "containeranalysis.googleapis.com:443" def test_container_analysis_host_with_port(): @@ -1167,182 +1522,238 @@ def test_container_analysis_host_with_port(): api_endpoint="containeranalysis.googleapis.com:8000" ), ) - assert client._transport._host == "containeranalysis.googleapis.com:8000" + assert client.transport._host == "containeranalysis.googleapis.com:8000" def test_container_analysis_grpc_transport_channel(): channel = grpc.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.ContainerAnalysisGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None def test_container_analysis_grpc_asyncio_transport_channel(): channel = aio.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.ContainerAnalysisGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_container_analysis_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContainerAnalysisGrpcTransport, + transports.ContainerAnalysisGrpcAsyncIOTransport, + ], +) +def test_container_analysis_transport_channel_mtls_with_client_cert_source( + transport_class, ): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ContainerAnalysisGrpcTransport, + transports.ContainerAnalysisGrpcAsyncIOTransport, + ], +) +def test_container_analysis_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + 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", autospec=True + ) 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, + ) - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel - transport = transports.ContainerAnalysisGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - 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=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, + +def test_common_billing_account_path(): + billing_account = "squid" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - assert transport.grpc_channel == mock_grpc_channel + actual = ContainerAnalysisClient.common_billing_account_path(billing_account) + assert expected == actual -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_container_analysis_grpc_asyncio_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ContainerAnalysisClient.common_billing_account_path(**expected) - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + # Check that the path construction is reversible. + actual = ContainerAnalysisClient.parse_common_billing_account_path(path) + assert expected == actual - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - transport = transports.ContainerAnalysisGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - 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=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, +def test_common_folder_path(): + folder = "whelk" + + expected = "folders/{folder}".format(folder=folder,) + actual = ContainerAnalysisClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ContainerAnalysisClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ContainerAnalysisClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + + expected = "organizations/{organization}".format(organization=organization,) + actual = ContainerAnalysisClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ContainerAnalysisClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ContainerAnalysisClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + + expected = "projects/{project}".format(project=project,) + actual = ContainerAnalysisClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ContainerAnalysisClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ContainerAnalysisClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, ) - assert transport.grpc_channel == mock_grpc_channel + actual = ContainerAnalysisClient.common_location_path(project, location) + assert expected == actual -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_container_analysis_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ContainerAnalysisClient.common_location_path(**expected) - # Mock google.auth.transport.grpc.SslCredentials 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), - ): - mock_cred = mock.Mock() - transport = transports.ContainerAnalysisGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + # Check that the path construction is reversible. + actual = ContainerAnalysisClient.parse_common_location_path(path) + assert expected == actual -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_container_analysis_grpc_asyncio_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() - # Mock google.auth.transport.grpc.SslCredentials 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), - ): - mock_cred = mock.Mock() - transport = transports.ContainerAnalysisGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, + with mock.patch.object( + transports.ContainerAnalysisTransport, "_prep_wrapped_messages" + ) as prep: + client = ContainerAnalysisClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ContainerAnalysisTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ContainerAnalysisClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, ) - assert transport.grpc_channel == mock_grpc_channel + prep.assert_called_once_with(client_info)