diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 23e106b..6ffef5f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ce3c1686bc81145c81dd269bd12c4025c6b275b22d14641358827334fddb1d72 -# created: 2022-08-29T17:28:30.441852797Z + digest: sha256:a31c2fd2f28e994254f6367b44e112722f3263247798ae222d7986bb12328ec3 diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 6988081..bd089a1 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -16,7 +16,7 @@ set -eo pipefail # Start the releasetool reporter -python3 -m pip install --require-hashes -r .kokoro/requirements.txt +python3 -m pip install --require-hashes -r github/python-batch/.kokoro/requirements.txt python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script # Disable buffering, so that the logs stream through. diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 4b29ef2..385f2d4 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -100,9 +100,9 @@ click==8.0.4 \ # via # gcp-docuploader # gcp-releasetool -colorlog==6.6.0 \ - --hash=sha256:344f73204009e4c83c5b6beb00b3c45dc70fcdae3c80db919e0a4171d006fde8 \ - --hash=sha256:351c51e866c86c3217f08e4b067a7974a678be78f07f85fc2d55b8babde6d94e +colorlog==6.7.0 \ + --hash=sha256:0d33ca236784a1ba3ff9c532d4964126d8a2c44f1f0cb1d2b0728196f512f662 \ + --hash=sha256:bd94bd21c1e13fac7bd3153f4bc3a7dc0eb0974b8bc2fdf1a989e474f6e582e5 # via # gcp-docuploader # nox @@ -152,9 +152,9 @@ gcp-docuploader==0.6.3 \ --hash=sha256:ba8c9d76b3bbac54b0311c503a373b00edc2dc02d6d54ea9507045adb8e870f7 \ --hash=sha256:c0f5aaa82ce1854a386197e4e359b120ad6d4e57ae2c812fce42219a3288026b # via -r requirements.in -gcp-releasetool==1.8.6 \ - --hash=sha256:42e51ab8e2e789bc8e22a03c09352962cd3452951c801a2230d564816630304a \ - --hash=sha256:a3518b79d1b243c494eac392a01c7fd65187fd6d52602dcab9b529bc934d4da1 +gcp-releasetool==1.8.7 \ + --hash=sha256:3d2a67c9db39322194afb3b427e9cb0476ce8f2a04033695f0aeb63979fc2b37 \ + --hash=sha256:5e4d28f66e90780d77f3ecf1e9155852b0c3b13cbccb08ab07e66b2357c8da8d # via -r requirements.in google-api-core==2.8.2 \ --hash=sha256:06f7244c640322b508b125903bb5701bebabce8832f85aba9335ec00b3d02edc \ @@ -241,6 +241,10 @@ importlib-metadata==4.12.0 \ # via # -r requirements.in # twine +jaraco-classes==3.2.2 \ + --hash=sha256:6745f113b0b588239ceb49532aa09c3ebb947433ce311ef2f8e3ad64ebb74594 \ + --hash=sha256:e6ef6fd3fcf4579a7a019d87d1e56a883f4e4c35cfe925f86731abc58804e647 + # via keyring jeepney==0.8.0 \ --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ --hash=sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755 @@ -251,9 +255,9 @@ jinja2==3.1.2 \ --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 # via gcp-releasetool -keyring==23.8.2 \ - --hash=sha256:0d9973f8891850f1ade5f26aafd06bb16865fbbae3fc56b0defb6a14a2624003 \ - --hash=sha256:10d2a8639663fe2090705a00b8c47c687cacdf97598ea9c11456679fa974473a +keyring==23.9.0 \ + --hash=sha256:4c32a31174faaee48f43a7e2c7e9c3216ec5e95acf22a2bebfb4a1d05056ee44 \ + --hash=sha256:98f060ec95ada2ab910c195a2d4317be6ef87936a766b239c46aa3c7aac4f0db # via # gcp-releasetool # twine @@ -299,6 +303,10 @@ markupsafe==2.1.1 \ --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 # via jinja2 +more-itertools==8.14.0 \ + --hash=sha256:1bc4f91ee5b1b31ac7ceacc17c09befe6a40a503907baf9c839c229b5095cfd2 \ + --hash=sha256:c09443cd3d5438b8dafccd867a6bc1cb0894389e90cb53d227456b0b0bccb750 + # via jaraco-classes nox==2022.8.7 \ --hash=sha256:1b894940551dc5c389f9271d197ca5d655d40bdc6ccf93ed6880e4042760a34b \ --hash=sha256:96cca88779e08282a699d672258ec01eb7c792d35bbbf538c723172bce23212c @@ -440,9 +448,9 @@ urllib3==1.26.12 \ # via # requests # twine -virtualenv==20.16.3 \ - --hash=sha256:4193b7bc8a6cd23e4eb251ac64f29b4398ab2c233531e66e40b19a6b7b0d30c1 \ - --hash=sha256:d86ea0bb50e06252d79e6c241507cb904fcd66090c3271381372d6221a3970f9 +virtualenv==20.16.4 \ + --hash=sha256:014f766e4134d0008dcaa1f95bafa0fb0f575795d07cae50b1bee514185d6782 \ + --hash=sha256:035ed57acce4ac35c82c9d8802202b0e71adac011a511ff650cbcf9635006a22 # via nox webencodings==0.5.1 \ --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ diff --git a/CHANGELOG.md b/CHANGELOG.md index dda9462..31c22a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## [0.3.0](https://github.com/googleapis/python-batch/compare/v0.2.0...v0.3.0) (2022-09-16) + + +### Features + +* Add support for REST transport ([#37](https://github.com/googleapis/python-batch/issues/37)) ([e48b9ba](https://github.com/googleapis/python-batch/commit/e48b9badf426683dc65c8ed3c570a9b5b44a119f)) + + +### Bug Fixes + +* **deps:** require google-api-core>=1.33.1,>=2.8.0 ([e48b9ba](https://github.com/googleapis/python-batch/commit/e48b9badf426683dc65c8ed3c570a9b5b44a119f)) +* **deps:** require protobuf >= 3.20.1 ([e48b9ba](https://github.com/googleapis/python-batch/commit/e48b9badf426683dc65c8ed3c570a9b5b44a119f)) + + +### Documentation + +* **samples:** Adding first sample code + tests ([#22](https://github.com/googleapis/python-batch/issues/22)) ([d8a4864](https://github.com/googleapis/python-batch/commit/d8a4864133ad41e8dec11870ab4a1a9bbbca3292)) + ## [0.2.0](https://github.com/googleapis/python-batch/compare/v0.1.2...v0.2.0) (2022-08-31) diff --git a/google/cloud/batch_v1/gapic_metadata.json b/google/cloud/batch_v1/gapic_metadata.json index 6f3fb08..2993812 100644 --- a/google/cloud/batch_v1/gapic_metadata.json +++ b/google/cloud/batch_v1/gapic_metadata.json @@ -76,6 +76,41 @@ ] } } + }, + "rest": { + "libraryClient": "BatchServiceClient", + "rpcs": { + "CreateJob": { + "methods": [ + "create_job" + ] + }, + "DeleteJob": { + "methods": [ + "delete_job" + ] + }, + "GetJob": { + "methods": [ + "get_job" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "ListJobs": { + "methods": [ + "list_jobs" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + } + } } } } diff --git a/google/cloud/batch_v1/services/batch_service/async_client.py b/google/cloud/batch_v1/services/batch_service/async_client.py index 5439ecd..8db6de0 100644 --- a/google/cloud/batch_v1/services/batch_service/async_client.py +++ b/google/cloud/batch_v1/services/batch_service/async_client.py @@ -231,6 +231,13 @@ async def create_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 async def sample_create_job(): @@ -348,6 +355,13 @@ async def get_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 async def sample_get_job(): @@ -447,6 +461,13 @@ async def delete_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 async def sample_delete_job(): @@ -560,6 +581,13 @@ async def list_jobs( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 async def sample_list_jobs(): @@ -672,6 +700,13 @@ async def get_task( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 async def sample_get_task(): @@ -771,6 +806,13 @@ async def list_tasks( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 async def sample_list_tasks(): diff --git a/google/cloud/batch_v1/services/batch_service/client.py b/google/cloud/batch_v1/services/batch_service/client.py index 0d86027..b4e0b88 100644 --- a/google/cloud/batch_v1/services/batch_service/client.py +++ b/google/cloud/batch_v1/services/batch_service/client.py @@ -50,6 +50,7 @@ from .transports.base import BatchServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import BatchServiceGrpcTransport from .transports.grpc_asyncio import BatchServiceGrpcAsyncIOTransport +from .transports.rest import BatchServiceRestTransport class BatchServiceClientMeta(type): @@ -63,6 +64,7 @@ class BatchServiceClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[BatchServiceTransport]] _transport_registry["grpc"] = BatchServiceGrpcTransport _transport_registry["grpc_asyncio"] = BatchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = BatchServiceRestTransport def get_transport_class( cls, @@ -409,6 +411,9 @@ def __init__( transport (Union[str, BatchServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the @@ -504,6 +509,13 @@ def create_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 def sample_create_job(): @@ -621,6 +633,13 @@ def get_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 def sample_get_job(): @@ -711,6 +730,13 @@ def delete_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 def sample_delete_job(): @@ -824,6 +850,13 @@ def list_jobs( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 def sample_list_jobs(): @@ -927,6 +960,13 @@ def get_task( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 def sample_get_task(): @@ -1017,6 +1057,13 @@ def list_tasks( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 def sample_list_tasks(): diff --git a/google/cloud/batch_v1/services/batch_service/transports/__init__.py b/google/cloud/batch_v1/services/batch_service/transports/__init__.py index 3ce4b5e..51fcc77 100644 --- a/google/cloud/batch_v1/services/batch_service/transports/__init__.py +++ b/google/cloud/batch_v1/services/batch_service/transports/__init__.py @@ -19,15 +19,20 @@ from .base import BatchServiceTransport from .grpc import BatchServiceGrpcTransport from .grpc_asyncio import BatchServiceGrpcAsyncIOTransport +from .rest import BatchServiceRestTransport +from .rest import BatchServiceRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[BatchServiceTransport]] _transport_registry["grpc"] = BatchServiceGrpcTransport _transport_registry["grpc_asyncio"] = BatchServiceGrpcAsyncIOTransport +_transport_registry["rest"] = BatchServiceRestTransport __all__ = ( "BatchServiceTransport", "BatchServiceGrpcTransport", "BatchServiceGrpcAsyncIOTransport", + "BatchServiceRestTransport", + "BatchServiceRestInterceptor", ) diff --git a/google/cloud/batch_v1/services/batch_service/transports/rest.py b/google/cloud/batch_v1/services/batch_service/transports/rest.py new file mode 100644 index 0000000..dac22d6 --- /dev/null +++ b/google/cloud/batch_v1/services/batch_service/transports/rest.py @@ -0,0 +1,1784 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.batch_v1.types import batch +from google.cloud.batch_v1.types import job +from google.cloud.batch_v1.types import job as gcb_job +from google.cloud.batch_v1.types import task +from google.longrunning import operations_pb2 # type: ignore + +from .base import BatchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class BatchServiceRestInterceptor: + """Interceptor for BatchService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the BatchServiceRestTransport. + + .. code-block:: python + class MyCustomBatchServiceInterceptor(BatchServiceRestInterceptor): + def pre_create_job(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_job(response): + logging.log(f"Received response: {response}") + + def pre_delete_job(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_job(response): + logging.log(f"Received response: {response}") + + def pre_get_job(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_job(response): + logging.log(f"Received response: {response}") + + def pre_get_task(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_task(response): + logging.log(f"Received response: {response}") + + def pre_list_jobs(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_jobs(response): + logging.log(f"Received response: {response}") + + def pre_list_tasks(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tasks(response): + logging.log(f"Received response: {response}") + + transport = BatchServiceRestTransport(interceptor=MyCustomBatchServiceInterceptor()) + client = BatchServiceClient(transport=transport) + + + """ + + def pre_create_job( + self, request: batch.CreateJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.CreateJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_create_job(self, response: gcb_job.Job) -> gcb_job.Job: + """Post-rpc interceptor for create_job + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_delete_job( + self, request: batch.DeleteJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.DeleteJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_delete_job( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_job + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_job( + self, request: batch.GetJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.GetJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_job(self, response: job.Job) -> job.Job: + """Post-rpc interceptor for get_job + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_task( + self, request: batch.GetTaskRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.GetTaskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_task + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_task(self, response: task.Task) -> task.Task: + """Post-rpc interceptor for get_task + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_jobs( + self, request: batch.ListJobsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.ListJobsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_jobs( + self, response: batch.ListJobsResponse + ) -> batch.ListJobsResponse: + """Post-rpc interceptor for list_jobs + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_tasks( + self, request: batch.ListTasksRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.ListTasksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tasks + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_tasks( + self, response: batch.ListTasksResponse + ) -> batch.ListTasksResponse: + """Post-rpc interceptor for list_tasks + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.Location: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.GetLocationRequest + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.ListLocationsResponse: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsRequest + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: iam_policy_pb2.GetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: iam_policy_pb2.SetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsRequest + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: operations_pb2.CancelOperationRequest + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_delete_operation( + self, response: operations_pb2.DeleteOperationRequest + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsRequest + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BatchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BatchServiceRestInterceptor + + +class BatchServiceRestTransport(BatchServiceTransport): + """REST backend transport for BatchService. + + Google Batch Service. + The service manages user submitted batch jobs and allocates + Google Compute Engine VM instances to run the jobs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "batch.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[BatchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or BatchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateJob(BatchServiceRestStub): + def __hash__(self): + return hash("CreateJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.CreateJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcb_job.Job: + r"""Call the create job method over HTTP. + + Args: + request (~.batch.CreateJobRequest): + The request object. CreateJob Request. + 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: + ~.gcb_job.Job: + The Cloud Batch Job description. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/jobs", + "body": "job", + }, + ] + request, metadata = self._interceptor.pre_create_job(request, metadata) + pb_request = batch.CreateJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcb_job.Job() + pb_resp = gcb_job.Job.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_job(resp) + return resp + + class _DeleteJob(BatchServiceRestStub): + def __hash__(self): + return hash("DeleteJob") + + def __call__( + self, + request: batch.DeleteJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete job method over HTTP. + + Args: + request (~.batch.DeleteJobRequest): + The request object. DeleteJob Request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/jobs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_job(request, metadata) + pb_request = batch.DeleteJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_job(resp) + return resp + + class _GetJob(BatchServiceRestStub): + def __hash__(self): + return hash("GetJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.GetJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Call the get job method over HTTP. + + Args: + request (~.batch.GetJobRequest): + The request object. GetJob Request. + 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: + ~.job.Job: + The Cloud Batch Job description. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/jobs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_job(request, metadata) + pb_request = batch.GetJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = job.Job() + pb_resp = job.Job.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_job(resp) + return resp + + class _GetTask(BatchServiceRestStub): + def __hash__(self): + return hash("GetTask") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.GetTaskRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> task.Task: + r"""Call the get task method over HTTP. + + Args: + request (~.batch.GetTaskRequest): + The request object. Request for a single Task by name. + 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: + ~.task.Task: + A Cloud Batch task. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/jobs/*/taskGroups/*/tasks/*}", + }, + ] + request, metadata = self._interceptor.pre_get_task(request, metadata) + pb_request = batch.GetTaskRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = task.Task() + pb_resp = task.Task.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_task(resp) + return resp + + class _ListJobs(BatchServiceRestStub): + def __hash__(self): + return hash("ListJobs") + + def __call__( + self, + request: batch.ListJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> batch.ListJobsResponse: + r"""Call the list jobs method over HTTP. + + Args: + request (~.batch.ListJobsRequest): + The request object. ListJob Request. + 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: + ~.batch.ListJobsResponse: + ListJob Response. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/jobs", + }, + ] + request, metadata = self._interceptor.pre_list_jobs(request, metadata) + pb_request = batch.ListJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = batch.ListJobsResponse() + pb_resp = batch.ListJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_jobs(resp) + return resp + + class _ListTasks(BatchServiceRestStub): + def __hash__(self): + return hash("ListTasks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.ListTasksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> batch.ListTasksResponse: + r"""Call the list tasks method over HTTP. + + Args: + request (~.batch.ListTasksRequest): + The request object. ListTasks Request. + 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: + ~.batch.ListTasksResponse: + ListTasks Response. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/jobs/*/taskGroups/*}/tasks", + }, + ] + request, metadata = self._interceptor.pre_list_tasks(request, metadata) + pb_request = batch.ListTasksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = batch.ListTasksResponse() + pb_resp = batch.ListTasksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tasks(resp) + return resp + + @property + def create_job(self) -> Callable[[batch.CreateJobRequest], gcb_job.Job]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_job( + self, + ) -> Callable[[batch.DeleteJobRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_job(self) -> Callable[[batch.GetJobRequest], job.Job]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_task(self) -> Callable[[batch.GetTaskRequest], task.Task]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTask(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_jobs(self) -> Callable[[batch.ListJobsRequest], batch.ListJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListJobs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tasks(self) -> Callable[[batch.ListTasksRequest], batch.ListTasksResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(BatchServiceRestStub): + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(BatchServiceRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(BatchServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/jobs/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/tasks/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/nodes/*}:getIamPolicy", + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(BatchServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/jobs/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/tasks/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/nodes/*}:setIamPolicy", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(BatchServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/jobs/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/tasks/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/nodes/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BatchServiceRestTransport",) diff --git a/google/cloud/batch_v1/types/job.py b/google/cloud/batch_v1/types/job.py index 3dd8b56..7f61abc 100644 --- a/google/cloud/batch_v1/types/job.py +++ b/google/cloud/batch_v1/types/job.py @@ -492,9 +492,7 @@ class Accelerator(proto.Message): count (int): The number of accelerators of this type. install_gpu_drivers (bool): - When true, Batch will install the GPU - drivers. This field will be ignored if - specified. + """ type_ = proto.Field( diff --git a/google/cloud/batch_v1alpha/gapic_metadata.json b/google/cloud/batch_v1alpha/gapic_metadata.json index d0e076f..43b7b05 100644 --- a/google/cloud/batch_v1alpha/gapic_metadata.json +++ b/google/cloud/batch_v1alpha/gapic_metadata.json @@ -76,6 +76,41 @@ ] } } + }, + "rest": { + "libraryClient": "BatchServiceClient", + "rpcs": { + "CreateJob": { + "methods": [ + "create_job" + ] + }, + "DeleteJob": { + "methods": [ + "delete_job" + ] + }, + "GetJob": { + "methods": [ + "get_job" + ] + }, + "GetTask": { + "methods": [ + "get_task" + ] + }, + "ListJobs": { + "methods": [ + "list_jobs" + ] + }, + "ListTasks": { + "methods": [ + "list_tasks" + ] + } + } } } } diff --git a/google/cloud/batch_v1alpha/services/batch_service/async_client.py b/google/cloud/batch_v1alpha/services/batch_service/async_client.py index 755d676..b30d247 100644 --- a/google/cloud/batch_v1alpha/services/batch_service/async_client.py +++ b/google/cloud/batch_v1alpha/services/batch_service/async_client.py @@ -231,6 +231,13 @@ async def create_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha async def sample_create_job(): @@ -348,6 +355,13 @@ async def get_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha async def sample_get_job(): @@ -447,6 +461,13 @@ async def delete_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha async def sample_delete_job(): @@ -560,6 +581,13 @@ async def list_jobs( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha async def sample_list_jobs(): @@ -672,6 +700,13 @@ async def get_task( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha async def sample_get_task(): @@ -771,6 +806,13 @@ async def list_tasks( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha async def sample_list_tasks(): diff --git a/google/cloud/batch_v1alpha/services/batch_service/client.py b/google/cloud/batch_v1alpha/services/batch_service/client.py index f1a40e1..2e875e6 100644 --- a/google/cloud/batch_v1alpha/services/batch_service/client.py +++ b/google/cloud/batch_v1alpha/services/batch_service/client.py @@ -50,6 +50,7 @@ from .transports.base import BatchServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import BatchServiceGrpcTransport from .transports.grpc_asyncio import BatchServiceGrpcAsyncIOTransport +from .transports.rest import BatchServiceRestTransport class BatchServiceClientMeta(type): @@ -63,6 +64,7 @@ class BatchServiceClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[BatchServiceTransport]] _transport_registry["grpc"] = BatchServiceGrpcTransport _transport_registry["grpc_asyncio"] = BatchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = BatchServiceRestTransport def get_transport_class( cls, @@ -409,6 +411,9 @@ def __init__( transport (Union[str, BatchServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the @@ -504,6 +509,13 @@ def create_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha def sample_create_job(): @@ -621,6 +633,13 @@ def get_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha def sample_get_job(): @@ -711,6 +730,13 @@ def delete_job( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha def sample_delete_job(): @@ -824,6 +850,13 @@ def list_jobs( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha def sample_list_jobs(): @@ -927,6 +960,13 @@ def get_task( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha def sample_get_task(): @@ -1017,6 +1057,13 @@ def list_tasks( .. code-block:: python + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha def sample_list_tasks(): diff --git a/google/cloud/batch_v1alpha/services/batch_service/transports/__init__.py b/google/cloud/batch_v1alpha/services/batch_service/transports/__init__.py index 3ce4b5e..51fcc77 100644 --- a/google/cloud/batch_v1alpha/services/batch_service/transports/__init__.py +++ b/google/cloud/batch_v1alpha/services/batch_service/transports/__init__.py @@ -19,15 +19,20 @@ from .base import BatchServiceTransport from .grpc import BatchServiceGrpcTransport from .grpc_asyncio import BatchServiceGrpcAsyncIOTransport +from .rest import BatchServiceRestTransport +from .rest import BatchServiceRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[BatchServiceTransport]] _transport_registry["grpc"] = BatchServiceGrpcTransport _transport_registry["grpc_asyncio"] = BatchServiceGrpcAsyncIOTransport +_transport_registry["rest"] = BatchServiceRestTransport __all__ = ( "BatchServiceTransport", "BatchServiceGrpcTransport", "BatchServiceGrpcAsyncIOTransport", + "BatchServiceRestTransport", + "BatchServiceRestInterceptor", ) diff --git a/google/cloud/batch_v1alpha/services/batch_service/transports/rest.py b/google/cloud/batch_v1alpha/services/batch_service/transports/rest.py new file mode 100644 index 0000000..66766ed --- /dev/null +++ b/google/cloud/batch_v1alpha/services/batch_service/transports/rest.py @@ -0,0 +1,1784 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.batch_v1alpha.types import batch +from google.cloud.batch_v1alpha.types import job +from google.cloud.batch_v1alpha.types import job as gcb_job +from google.cloud.batch_v1alpha.types import task +from google.longrunning import operations_pb2 # type: ignore + +from .base import BatchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class BatchServiceRestInterceptor: + """Interceptor for BatchService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the BatchServiceRestTransport. + + .. code-block:: python + class MyCustomBatchServiceInterceptor(BatchServiceRestInterceptor): + def pre_create_job(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_job(response): + logging.log(f"Received response: {response}") + + def pre_delete_job(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_job(response): + logging.log(f"Received response: {response}") + + def pre_get_job(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_job(response): + logging.log(f"Received response: {response}") + + def pre_get_task(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_task(response): + logging.log(f"Received response: {response}") + + def pre_list_jobs(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_jobs(response): + logging.log(f"Received response: {response}") + + def pre_list_tasks(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tasks(response): + logging.log(f"Received response: {response}") + + transport = BatchServiceRestTransport(interceptor=MyCustomBatchServiceInterceptor()) + client = BatchServiceClient(transport=transport) + + + """ + + def pre_create_job( + self, request: batch.CreateJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.CreateJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_create_job(self, response: gcb_job.Job) -> gcb_job.Job: + """Post-rpc interceptor for create_job + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_delete_job( + self, request: batch.DeleteJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.DeleteJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_delete_job( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_job + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_job( + self, request: batch.GetJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.GetJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_job(self, response: job.Job) -> job.Job: + """Post-rpc interceptor for get_job + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_task( + self, request: batch.GetTaskRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.GetTaskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_task + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_task(self, response: task.Task) -> task.Task: + """Post-rpc interceptor for get_task + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_jobs( + self, request: batch.ListJobsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.ListJobsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_jobs( + self, response: batch.ListJobsResponse + ) -> batch.ListJobsResponse: + """Post-rpc interceptor for list_jobs + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_tasks( + self, request: batch.ListTasksRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[batch.ListTasksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tasks + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_tasks( + self, response: batch.ListTasksResponse + ) -> batch.ListTasksResponse: + """Post-rpc interceptor for list_tasks + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.Location: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.GetLocationRequest + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.ListLocationsResponse: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsRequest + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: iam_policy_pb2.GetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: iam_policy_pb2.SetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsRequest + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: operations_pb2.CancelOperationRequest + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_delete_operation( + self, response: operations_pb2.DeleteOperationRequest + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BatchService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsRequest + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the BatchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BatchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BatchServiceRestInterceptor + + +class BatchServiceRestTransport(BatchServiceTransport): + """REST backend transport for BatchService. + + Google Batch Service. + The service manages user submitted batch jobs and allocates + Google Compute Engine VM instances to run the jobs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "batch.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[BatchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or BatchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateJob(BatchServiceRestStub): + def __hash__(self): + return hash("CreateJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.CreateJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcb_job.Job: + r"""Call the create job method over HTTP. + + Args: + request (~.batch.CreateJobRequest): + The request object. CreateJob Request. + 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: + ~.gcb_job.Job: + The Cloud Batch Job description. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*}/jobs", + "body": "job", + }, + ] + request, metadata = self._interceptor.pre_create_job(request, metadata) + pb_request = batch.CreateJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcb_job.Job() + pb_resp = gcb_job.Job.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_job(resp) + return resp + + class _DeleteJob(BatchServiceRestStub): + def __hash__(self): + return hash("DeleteJob") + + def __call__( + self, + request: batch.DeleteJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete job method over HTTP. + + Args: + request (~.batch.DeleteJobRequest): + The request object. DeleteJob Request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/jobs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_job(request, metadata) + pb_request = batch.DeleteJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_job(resp) + return resp + + class _GetJob(BatchServiceRestStub): + def __hash__(self): + return hash("GetJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.GetJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> job.Job: + r"""Call the get job method over HTTP. + + Args: + request (~.batch.GetJobRequest): + The request object. GetJob Request. + 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: + ~.job.Job: + The Cloud Batch Job description. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/jobs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_job(request, metadata) + pb_request = batch.GetJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = job.Job() + pb_resp = job.Job.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_job(resp) + return resp + + class _GetTask(BatchServiceRestStub): + def __hash__(self): + return hash("GetTask") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.GetTaskRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> task.Task: + r"""Call the get task method over HTTP. + + Args: + request (~.batch.GetTaskRequest): + The request object. Request for a single Task by name. + 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: + ~.task.Task: + A Cloud Batch task. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/jobs/*/taskGroups/*/tasks/*}", + }, + ] + request, metadata = self._interceptor.pre_get_task(request, metadata) + pb_request = batch.GetTaskRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = task.Task() + pb_resp = task.Task.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_task(resp) + return resp + + class _ListJobs(BatchServiceRestStub): + def __hash__(self): + return hash("ListJobs") + + def __call__( + self, + request: batch.ListJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> batch.ListJobsResponse: + r"""Call the list jobs method over HTTP. + + Args: + request (~.batch.ListJobsRequest): + The request object. ListJob Request. + 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: + ~.batch.ListJobsResponse: + ListJob Response. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*}/jobs", + }, + ] + request, metadata = self._interceptor.pre_list_jobs(request, metadata) + pb_request = batch.ListJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = batch.ListJobsResponse() + pb_resp = batch.ListJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_jobs(resp) + return resp + + class _ListTasks(BatchServiceRestStub): + def __hash__(self): + return hash("ListTasks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: batch.ListTasksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> batch.ListTasksResponse: + r"""Call the list tasks method over HTTP. + + Args: + request (~.batch.ListTasksRequest): + The request object. ListTasks Request. + 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: + ~.batch.ListTasksResponse: + ListTasks Response. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*/jobs/*/taskGroups/*}/tasks", + }, + ] + request, metadata = self._interceptor.pre_list_tasks(request, metadata) + pb_request = batch.ListTasksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = batch.ListTasksResponse() + pb_resp = batch.ListTasksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tasks(resp) + return resp + + @property + def create_job(self) -> Callable[[batch.CreateJobRequest], gcb_job.Job]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_job( + self, + ) -> Callable[[batch.DeleteJobRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_job(self) -> Callable[[batch.GetJobRequest], job.Job]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_task(self) -> Callable[[batch.GetTaskRequest], task.Task]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTask(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_jobs(self) -> Callable[[batch.ListJobsRequest], batch.ListJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListJobs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tasks(self) -> Callable[[batch.ListTasksRequest], batch.ListTasksResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(BatchServiceRestStub): + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(BatchServiceRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(BatchServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{resource=projects/*/locations/*/jobs/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1alpha/{resource=projects/*/locations/*/tasks/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1alpha/{resource=projects/*/locations/*/nodes/*}:getIamPolicy", + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(BatchServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{resource=projects/*/locations/*/jobs/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{resource=projects/*/locations/*/tasks/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{resource=projects/*/locations/*/nodes/*}:setIamPolicy", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(BatchServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{resource=projects/*/locations/*/jobs/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{resource=projects/*/locations/*/tasks/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{resource=projects/*/locations/*/nodes/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(BatchServiceRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BatchServiceRestTransport",) diff --git a/google/cloud/batch_v1alpha/types/job.py b/google/cloud/batch_v1alpha/types/job.py index 43568dd..0d9036e 100644 --- a/google/cloud/batch_v1alpha/types/job.py +++ b/google/cloud/batch_v1alpha/types/job.py @@ -582,9 +582,7 @@ class Accelerator(proto.Message): count (int): The number of accelerators of this type. install_gpu_drivers (bool): - When true, Batch will install the GPU - drivers. This field will be ignored if - specified. + """ type_ = proto.Field( diff --git a/mypy.ini b/mypy.ini index 4505b48..574c5ae 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,3 +1,3 @@ [mypy] -python_version = 3.6 +python_version = 3.7 namespace_packages = True diff --git a/renovate.json b/renovate.json index 566a70f..39b2a0e 100644 --- a/renovate.json +++ b/renovate.json @@ -5,7 +5,7 @@ ":preserveSemverRanges", ":disableDependencyDashboard" ], - "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt"], + "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt", "setup.py"], "pip_requirements": { "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] } diff --git a/samples/__init__.py b/samples/__init__.py new file mode 100644 index 0000000..4bbe0ff --- /dev/null +++ b/samples/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/samples/generated_samples/batch_v1_generated_batch_service_create_job_async.py b/samples/generated_samples/batch_v1_generated_batch_service_create_job_async.py index b8b5d54..eb8d475 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_create_job_async.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_create_job_async.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_CreateJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync.py b/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync.py index bf4685c..77f1ed0 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_CreateJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync_2bc66fef.py b/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync_2bc66fef.py new file mode 100644 index 0000000..e3ae8a7 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync_2bc66fef.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_CreateJob_sync_2bc66fef] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_create_job(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.CreateJobRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_CreateJob_sync_2bc66fef] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync_6f38dd76.py b/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync_6f38dd76.py new file mode 100644 index 0000000..d746f6c --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_create_job_sync_6f38dd76.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_CreateJob_sync_6f38dd76] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_create_job(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.CreateJobRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_CreateJob_sync_6f38dd76] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_delete_job_async.py b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_async.py index 5d64e17..0af8acf 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_delete_job_async.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_async.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_DeleteJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync.py b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync.py index 4546488..bdd3821 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_DeleteJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync_0196009c.py b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync_0196009c.py new file mode 100644 index 0000000..b00884b --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync_0196009c.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_DeleteJob_sync_0196009c] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_delete_job(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.DeleteJobRequest( + ) + + # Make the request + operation = client.delete_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_DeleteJob_sync_0196009c] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync_91684552.py b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync_91684552.py new file mode 100644 index 0000000..664bb1f --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_delete_job_sync_91684552.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_DeleteJob_sync_91684552] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_delete_job(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.DeleteJobRequest( + ) + + # Make the request + operation = client.delete_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_DeleteJob_sync_91684552] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_job_async.py b/samples/generated_samples/batch_v1_generated_batch_service_get_job_async.py index c73717f..bacea06 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_get_job_async.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_job_async.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_GetJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync.py b/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync.py index fe53c50..c4e8189 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_GetJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync_97ad7e29.py b/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync_97ad7e29.py new file mode 100644 index 0000000..7f399fb --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync_97ad7e29.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_GetJob_sync_97ad7e29] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_get_job(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.GetJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_GetJob_sync_97ad7e29] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync_b06cc31b.py b/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync_b06cc31b.py new file mode 100644 index 0000000..b4d2f94 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_job_sync_b06cc31b.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_GetJob_sync_b06cc31b] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_get_job(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.GetJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_GetJob_sync_b06cc31b] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_task_async.py b/samples/generated_samples/batch_v1_generated_batch_service_get_task_async.py index fc73048..154dc79 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_get_task_async.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_task_async.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_GetTask_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync.py b/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync.py index 0649465..059a72f 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_GetTask_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync_bbff024f.py b/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync_bbff024f.py new file mode 100644 index 0000000..9fd3103 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync_bbff024f.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_GetTask_sync_bbff024f] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_get_task(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = client.get_task(request=request) + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_GetTask_sync_bbff024f] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync_fa6ae8a7.py b/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync_fa6ae8a7.py new file mode 100644 index 0000000..74f5d09 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_get_task_sync_fa6ae8a7.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_GetTask_sync_fa6ae8a7] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_get_task(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = client.get_task(request=request) + + # Handle the response + print(response) + +# [END batch_v1_generated_BatchService_GetTask_sync_fa6ae8a7] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_async.py b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_async.py index 6053925..db637c1 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_async.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_async.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_ListJobs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync.py b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync.py index 47dd7ec..83dfb69 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_ListJobs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync_2430eb9c.py b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync_2430eb9c.py new file mode 100644 index 0000000..4c5643c --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync_2430eb9c.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_ListJobs_sync_2430eb9c] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_list_jobs(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.ListJobsRequest( + ) + + # Make the request + page_result = client.list_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1_generated_BatchService_ListJobs_sync_2430eb9c] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync_d2310594.py b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync_d2310594.py new file mode 100644 index 0000000..5fffe77 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_jobs_sync_d2310594.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_ListJobs_sync_d2310594] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_list_jobs(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.ListJobsRequest( + ) + + # Make the request + page_result = client.list_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1_generated_BatchService_ListJobs_sync_d2310594] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_async.py b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_async.py index 51681d9..6e90626 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_async.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_async.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_ListTasks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync.py b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync.py index d888a57..79e02ba 100644 --- a/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync.py +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync.py @@ -24,6 +24,13 @@ # [START batch_v1_generated_BatchService_ListTasks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1 diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync_9b3f04d1.py b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync_9b3f04d1.py new file mode 100644 index 0000000..b8b50f2 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync_9b3f04d1.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_ListTasks_sync_9b3f04d1] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_list_tasks(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1_generated_BatchService_ListTasks_sync_9b3f04d1] diff --git a/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync_adf409cc.py b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync_adf409cc.py new file mode 100644 index 0000000..3e5bad8 --- /dev/null +++ b/samples/generated_samples/batch_v1_generated_batch_service_list_tasks_sync_adf409cc.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1_generated_BatchService_ListTasks_sync_adf409cc] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1 + + +def sample_list_tasks(): + # Create a client + client = batch_v1.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1_generated_BatchService_ListTasks_sync_adf409cc] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_async.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_async.py index 1d89197..b1602d7 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_async.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_async.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_CreateJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync.py index 39e581f..17a89f9 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_CreateJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync_eb4fa717.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync_eb4fa717.py new file mode 100644 index 0000000..90801c0 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync_eb4fa717.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_CreateJob_sync_eb4fa717] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_create_job(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.CreateJobRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_CreateJob_sync_eb4fa717] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync_ee80cfe8.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync_ee80cfe8.py new file mode 100644 index 0000000..1c6700a --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_create_job_sync_ee80cfe8.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_CreateJob_sync_ee80cfe8] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_create_job(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.CreateJobRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_CreateJob_sync_ee80cfe8] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_async.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_async.py index 6f4e7ee..03efd1c 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_async.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_async.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_DeleteJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync.py index 7bb7b4d..b47ca5e 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_DeleteJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync_18fb9154.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync_18fb9154.py new file mode 100644 index 0000000..52fb6a7 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync_18fb9154.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_DeleteJob_sync_18fb9154] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_delete_job(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.DeleteJobRequest( + ) + + # Make the request + operation = client.delete_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_DeleteJob_sync_18fb9154] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync_affefd11.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync_affefd11.py new file mode 100644 index 0000000..0b33e67 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_delete_job_sync_affefd11.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_DeleteJob_sync_affefd11] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_delete_job(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.DeleteJobRequest( + ) + + # Make the request + operation = client.delete_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_DeleteJob_sync_affefd11] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_async.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_async.py index ff9f938..0b96db9 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_async.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_async.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_GetJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync.py index 07a0f0f..9a56b65 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_GetJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync_1014e8c7.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync_1014e8c7.py new file mode 100644 index 0000000..0a6aa64 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync_1014e8c7.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_GetJob_sync_1014e8c7] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_get_job(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.GetJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_GetJob_sync_1014e8c7] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync_17387e0a.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync_17387e0a.py new file mode 100644 index 0000000..0eb3247 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_job_sync_17387e0a.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_GetJob_sync_17387e0a] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_get_job(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.GetJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_job(request=request) + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_GetJob_sync_17387e0a] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_async.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_async.py index 6f5471f..99e13d8 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_async.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_async.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_GetTask_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync.py index 1a36eda..bf8528f 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_GetTask_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync_29b69ea9.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync_29b69ea9.py new file mode 100644 index 0000000..a969578 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync_29b69ea9.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_GetTask_sync_29b69ea9] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_get_task(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = client.get_task(request=request) + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_GetTask_sync_29b69ea9] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync_657a0e4c.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync_657a0e4c.py new file mode 100644 index 0000000..2404c52 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_get_task_sync_657a0e4c.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTask +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_GetTask_sync_657a0e4c] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_get_task(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.GetTaskRequest( + name="name_value", + ) + + # Make the request + response = client.get_task(request=request) + + # Handle the response + print(response) + +# [END batch_v1alpha_generated_BatchService_GetTask_sync_657a0e4c] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_async.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_async.py index 39f3b90..ea3b072 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_async.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_async.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_ListJobs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync.py index ed142e8..8a7a738 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_ListJobs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync_21301b63.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync_21301b63.py new file mode 100644 index 0000000..799f233 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync_21301b63.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_ListJobs_sync_21301b63] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_list_jobs(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.ListJobsRequest( + ) + + # Make the request + page_result = client.list_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1alpha_generated_BatchService_ListJobs_sync_21301b63] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync_830dac29.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync_830dac29.py new file mode 100644 index 0000000..03cb615 --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_jobs_sync_830dac29.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_ListJobs_sync_830dac29] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_list_jobs(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.ListJobsRequest( + ) + + # Make the request + page_result = client.list_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1alpha_generated_BatchService_ListJobs_sync_830dac29] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_async.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_async.py index 8ecdaa4..a3f7cdf 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_async.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_async.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_ListTasks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync.py index b2b4f48..1e2f6c3 100644 --- a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync.py +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync.py @@ -24,6 +24,13 @@ # [START batch_v1alpha_generated_BatchService_ListTasks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import batch_v1alpha diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync_97ddc579.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync_97ddc579.py new file mode 100644 index 0000000..8c0ac9e --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync_97ddc579.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_ListTasks_sync_97ddc579] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_list_tasks(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1alpha_generated_BatchService_ListTasks_sync_97ddc579] diff --git a/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync_af95f032.py b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync_af95f032.py new file mode 100644 index 0000000..c584fda --- /dev/null +++ b/samples/generated_samples/batch_v1alpha_generated_batch_service_list_tasks_sync_af95f032.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTasks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-batch + + +# [START batch_v1alpha_generated_BatchService_ListTasks_sync_af95f032] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import batch_v1alpha + + +def sample_list_tasks(): + # Create a client + client = batch_v1alpha.BatchServiceClient() + + # Initialize request argument(s) + request = batch_v1alpha.ListTasksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tasks(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END batch_v1alpha_generated_BatchService_ListTasks_sync_af95f032] diff --git a/samples/generated_samples/snippet_metadata_batch_v1.json b/samples/generated_samples/snippet_metadata_batch_v1.json index 71090ed..9a7609f 100644 --- a/samples/generated_samples/snippet_metadata_batch_v1.json +++ b/samples/generated_samples/snippet_metadata_batch_v1.json @@ -67,33 +67,33 @@ "regionTag": "batch_v1_generated_BatchService_CreateJob_async", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], @@ -149,43 +149,131 @@ "shortName": "create_job" }, "description": "Sample for CreateJob", - "file": "batch_v1_generated_batch_service_create_job_sync.py", + "file": "batch_v1_generated_batch_service_create_job_sync_2bc66fef.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "batch_v1_generated_BatchService_CreateJob_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1_generated_batch_service_create_job_sync_2bc66fef.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1.BatchServiceClient.create_job", + "method": { + "fullName": "google.cloud.batch.v1.BatchService.CreateJob", + "service": { + "fullName": "google.cloud.batch.v1.BatchService", + "shortName": "BatchService" + }, + "shortName": "CreateJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1.types.CreateJobRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "job", + "type": "google.cloud.batch_v1.types.Job" + }, + { + "name": "job_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.batch_v1.types.Job", + "shortName": "create_job" + }, + "description": "Sample for CreateJob", + "file": "batch_v1_generated_batch_service_create_job_sync_6f38dd76.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1_generated_BatchService_CreateJob_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, { "end": 45, - "start": 42, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_create_job_sync.py" + "title": "batch_v1_generated_batch_service_create_job_sync_6f38dd76.py" }, { "canonical": true, @@ -207,7 +295,408 @@ "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.DeleteJobRequest" + "type": "google.cloud.batch_v1.types.DeleteJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_job" + }, + "description": "Sample for DeleteJob", + "file": "batch_v1_generated_batch_service_delete_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1_generated_BatchService_DeleteJob_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1_generated_batch_service_delete_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1.BatchServiceClient.delete_job", + "method": { + "fullName": "google.cloud.batch.v1.BatchService.DeleteJob", + "service": { + "fullName": "google.cloud.batch.v1.BatchService", + "shortName": "BatchService" + }, + "shortName": "DeleteJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1.types.DeleteJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_job" + }, + "description": "Sample for DeleteJob", + "file": "batch_v1_generated_batch_service_delete_job_sync_91684552.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1_generated_BatchService_DeleteJob_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1_generated_batch_service_delete_job_sync_91684552.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1.BatchServiceClient.delete_job", + "method": { + "fullName": "google.cloud.batch.v1.BatchService.DeleteJob", + "service": { + "fullName": "google.cloud.batch.v1.BatchService", + "shortName": "BatchService" + }, + "shortName": "DeleteJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1.types.DeleteJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_job" + }, + "description": "Sample for DeleteJob", + "file": "batch_v1_generated_batch_service_delete_job_sync_0196009c.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1_generated_BatchService_DeleteJob_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1_generated_batch_service_delete_job_sync_0196009c.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", + "shortName": "BatchServiceAsyncClient" + }, + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.get_job", + "method": { + "fullName": "google.cloud.batch.v1.BatchService.GetJob", + "service": { + "fullName": "google.cloud.batch.v1.BatchService", + "shortName": "BatchService" + }, + "shortName": "GetJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1.types.GetJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.batch_v1.types.Job", + "shortName": "get_job" + }, + "description": "Sample for GetJob", + "file": "batch_v1_generated_batch_service_get_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1_generated_BatchService_GetJob_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1_generated_batch_service_get_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1.BatchServiceClient.get_job", + "method": { + "fullName": "google.cloud.batch.v1.BatchService.GetJob", + "service": { + "fullName": "google.cloud.batch.v1.BatchService", + "shortName": "BatchService" + }, + "shortName": "GetJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1.types.GetJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.batch_v1.types.Job", + "shortName": "get_job" + }, + "description": "Sample for GetJob", + "file": "batch_v1_generated_batch_service_get_job_sync_97ad7e29.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1_generated_BatchService_GetJob_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1_generated_batch_service_get_job_sync_97ad7e29.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1.BatchServiceClient.get_job", + "method": { + "fullName": "google.cloud.batch.v1.BatchService.GetJob", + "service": { + "fullName": "google.cloud.batch.v1.BatchService", + "shortName": "BatchService" + }, + "shortName": "GetJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1.types.GetJobRequest" }, { "name": "name", @@ -226,68 +715,69 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_job" + "resultType": "google.cloud.batch_v1.types.Job", + "shortName": "get_job" }, - "description": "Sample for DeleteJob", - "file": "batch_v1_generated_batch_service_delete_job_async.py", + "description": "Sample for GetJob", + "file": "batch_v1_generated_batch_service_get_job_sync_b06cc31b.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_DeleteJob_async", + "regionTag": "batch_v1_generated_BatchService_GetJob_sync", "segments": [ { - "end": 47, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 38, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_delete_job_async.py" + "title": "batch_v1_generated_batch_service_get_job_sync_b06cc31b.py" }, { "canonical": true, "clientMethod": { + "async": true, "client": { - "fullName": "google.cloud.batch_v1.BatchServiceClient", - "shortName": "BatchServiceClient" + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", + "shortName": "BatchServiceAsyncClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceClient.delete_job", + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.get_task", "method": { - "fullName": "google.cloud.batch.v1.BatchService.DeleteJob", + "fullName": "google.cloud.batch.v1.BatchService.GetTask", "service": { "fullName": "google.cloud.batch.v1.BatchService", "shortName": "BatchService" }, - "shortName": "DeleteJob" + "shortName": "GetTask" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.DeleteJobRequest" + "type": "google.cloud.batch_v1.types.GetTaskRequest" }, { "name": "name", @@ -306,69 +796,68 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_job" + "resultType": "google.cloud.batch_v1.types.Task", + "shortName": "get_task" }, - "description": "Sample for DeleteJob", - "file": "batch_v1_generated_batch_service_delete_job_sync.py", + "description": "Sample for GetTask", + "file": "batch_v1_generated_batch_service_get_task_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_DeleteJob_sync", + "regionTag": "batch_v1_generated_BatchService_GetTask_async", "segments": [ { - "end": 47, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 38, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_delete_job_sync.py" + "title": "batch_v1_generated_batch_service_get_task_async.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", - "shortName": "BatchServiceAsyncClient" + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.get_job", + "fullName": "google.cloud.batch_v1.BatchServiceClient.get_task", "method": { - "fullName": "google.cloud.batch.v1.BatchService.GetJob", + "fullName": "google.cloud.batch.v1.BatchService.GetTask", "service": { "fullName": "google.cloud.batch.v1.BatchService", "shortName": "BatchService" }, - "shortName": "GetJob" + "shortName": "GetTask" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.GetJobRequest" + "type": "google.cloud.batch_v1.types.GetTaskRequest" }, { "name": "name", @@ -387,47 +876,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.types.Job", - "shortName": "get_job" + "resultType": "google.cloud.batch_v1.types.Task", + "shortName": "get_task" }, - "description": "Sample for GetJob", - "file": "batch_v1_generated_batch_service_get_job_async.py", + "description": "Sample for GetTask", + "file": "batch_v1_generated_batch_service_get_task_sync_bbff024f.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_GetJob_async", + "regionTag": "batch_v1_generated_BatchService_GetTask_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_get_job_async.py" + "title": "batch_v1_generated_batch_service_get_task_sync_bbff024f.py" }, { "canonical": true, @@ -436,19 +925,19 @@ "fullName": "google.cloud.batch_v1.BatchServiceClient", "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceClient.get_job", + "fullName": "google.cloud.batch_v1.BatchServiceClient.get_task", "method": { - "fullName": "google.cloud.batch.v1.BatchService.GetJob", + "fullName": "google.cloud.batch.v1.BatchService.GetTask", "service": { "fullName": "google.cloud.batch.v1.BatchService", "shortName": "BatchService" }, - "shortName": "GetJob" + "shortName": "GetTask" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.GetJobRequest" + "type": "google.cloud.batch_v1.types.GetTaskRequest" }, { "name": "name", @@ -467,47 +956,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.types.Job", - "shortName": "get_job" + "resultType": "google.cloud.batch_v1.types.Task", + "shortName": "get_task" }, - "description": "Sample for GetJob", - "file": "batch_v1_generated_batch_service_get_job_sync.py", + "description": "Sample for GetTask", + "file": "batch_v1_generated_batch_service_get_task_sync_fa6ae8a7.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_GetJob_sync", + "regionTag": "batch_v1_generated_BatchService_GetTask_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_get_job_sync.py" + "title": "batch_v1_generated_batch_service_get_task_sync_fa6ae8a7.py" }, { "canonical": true, @@ -517,22 +1006,22 @@ "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", "shortName": "BatchServiceAsyncClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.get_task", + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.list_jobs", "method": { - "fullName": "google.cloud.batch.v1.BatchService.GetTask", + "fullName": "google.cloud.batch.v1.BatchService.ListJobs", "service": { "fullName": "google.cloud.batch.v1.BatchService", "shortName": "BatchService" }, - "shortName": "GetTask" + "shortName": "ListJobs" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.GetTaskRequest" + "type": "google.cloud.batch_v1.types.ListJobsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -548,47 +1037,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.types.Task", - "shortName": "get_task" + "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListJobsAsyncPager", + "shortName": "list_jobs" }, - "description": "Sample for GetTask", - "file": "batch_v1_generated_batch_service_get_task_async.py", + "description": "Sample for ListJobs", + "file": "batch_v1_generated_batch_service_list_jobs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_GetTask_async", + "regionTag": "batch_v1_generated_BatchService_ListJobs_async", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 44, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_get_task_async.py" + "title": "batch_v1_generated_batch_service_list_jobs_async.py" }, { "canonical": true, @@ -597,22 +1086,22 @@ "fullName": "google.cloud.batch_v1.BatchServiceClient", "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceClient.get_task", + "fullName": "google.cloud.batch_v1.BatchServiceClient.list_jobs", "method": { - "fullName": "google.cloud.batch.v1.BatchService.GetTask", + "fullName": "google.cloud.batch.v1.BatchService.ListJobs", "service": { "fullName": "google.cloud.batch.v1.BatchService", "shortName": "BatchService" }, - "shortName": "GetTask" + "shortName": "ListJobs" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.GetTaskRequest" + "type": "google.cloud.batch_v1.types.ListJobsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -628,57 +1117,56 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.types.Task", - "shortName": "get_task" + "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListJobsPager", + "shortName": "list_jobs" }, - "description": "Sample for GetTask", - "file": "batch_v1_generated_batch_service_get_task_sync.py", + "description": "Sample for ListJobs", + "file": "batch_v1_generated_batch_service_list_jobs_sync_d2310594.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_GetTask_sync", + "regionTag": "batch_v1_generated_BatchService_ListJobs_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 44, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_get_task_sync.py" + "title": "batch_v1_generated_batch_service_list_jobs_sync_d2310594.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", - "shortName": "BatchServiceAsyncClient" + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.list_jobs", + "fullName": "google.cloud.batch_v1.BatchServiceClient.list_jobs", "method": { "fullName": "google.cloud.batch.v1.BatchService.ListJobs", "service": { @@ -709,68 +1197,69 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListJobsAsyncPager", + "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListJobsPager", "shortName": "list_jobs" }, "description": "Sample for ListJobs", - "file": "batch_v1_generated_batch_service_list_jobs_async.py", + "file": "batch_v1_generated_batch_service_list_jobs_sync_2430eb9c.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_ListJobs_async", + "regionTag": "batch_v1_generated_BatchService_ListJobs_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 44, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 40, - "start": 38, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 41, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_list_jobs_async.py" + "title": "batch_v1_generated_batch_service_list_jobs_sync_2430eb9c.py" }, { "canonical": true, "clientMethod": { + "async": true, "client": { - "fullName": "google.cloud.batch_v1.BatchServiceClient", - "shortName": "BatchServiceClient" + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", + "shortName": "BatchServiceAsyncClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceClient.list_jobs", + "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.list_tasks", "method": { - "fullName": "google.cloud.batch.v1.BatchService.ListJobs", + "fullName": "google.cloud.batch.v1.BatchService.ListTasks", "service": { "fullName": "google.cloud.batch.v1.BatchService", "shortName": "BatchService" }, - "shortName": "ListJobs" + "shortName": "ListTasks" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1.types.ListJobsRequest" + "type": "google.cloud.batch_v1.types.ListTasksRequest" }, { "name": "parent", @@ -789,57 +1278,56 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListJobsPager", - "shortName": "list_jobs" + "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListTasksAsyncPager", + "shortName": "list_tasks" }, - "description": "Sample for ListJobs", - "file": "batch_v1_generated_batch_service_list_jobs_sync.py", + "description": "Sample for ListTasks", + "file": "batch_v1_generated_batch_service_list_tasks_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_ListJobs_sync", + "regionTag": "batch_v1_generated_BatchService_ListTasks_async", "segments": [ { - "end": 44, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 40, - "start": 38, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 41, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_list_jobs_sync.py" + "title": "batch_v1_generated_batch_service_list_tasks_async.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient", - "shortName": "BatchServiceAsyncClient" + "fullName": "google.cloud.batch_v1.BatchServiceClient", + "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1.BatchServiceAsyncClient.list_tasks", + "fullName": "google.cloud.batch_v1.BatchServiceClient.list_tasks", "method": { "fullName": "google.cloud.batch.v1.BatchService.ListTasks", "service": { @@ -870,47 +1358,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListTasksAsyncPager", + "resultType": "google.cloud.batch_v1.services.batch_service.pagers.ListTasksPager", "shortName": "list_tasks" }, "description": "Sample for ListTasks", - "file": "batch_v1_generated_batch_service_list_tasks_async.py", + "file": "batch_v1_generated_batch_service_list_tasks_sync_adf409cc.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1_generated_BatchService_ListTasks_async", + "regionTag": "batch_v1_generated_BatchService_ListTasks_sync", "segments": [ { - "end": 45, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 45, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 46, - "start": 42, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_list_tasks_async.py" + "title": "batch_v1_generated_batch_service_list_tasks_sync_adf409cc.py" }, { "canonical": true, @@ -954,43 +1442,43 @@ "shortName": "list_tasks" }, "description": "Sample for ListTasks", - "file": "batch_v1_generated_batch_service_list_tasks_sync.py", + "file": "batch_v1_generated_batch_service_list_tasks_sync_9b3f04d1.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "batch_v1_generated_BatchService_ListTasks_sync", "segments": [ { - "end": 45, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 45, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 46, - "start": 42, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1_generated_batch_service_list_tasks_sync.py" + "title": "batch_v1_generated_batch_service_list_tasks_sync_9b3f04d1.py" } ] } diff --git a/samples/generated_samples/snippet_metadata_batch_v1alpha.json b/samples/generated_samples/snippet_metadata_batch_v1alpha.json index 329b3e3..5a49807 100644 --- a/samples/generated_samples/snippet_metadata_batch_v1alpha.json +++ b/samples/generated_samples/snippet_metadata_batch_v1alpha.json @@ -67,33 +67,33 @@ "regionTag": "batch_v1alpha_generated_BatchService_CreateJob_async", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], @@ -149,43 +149,131 @@ "shortName": "create_job" }, "description": "Sample for CreateJob", - "file": "batch_v1alpha_generated_batch_service_create_job_sync.py", + "file": "batch_v1alpha_generated_batch_service_create_job_sync_eb4fa717.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "batch_v1alpha_generated_BatchService_CreateJob_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1alpha_generated_batch_service_create_job_sync_eb4fa717.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.create_job", + "method": { + "fullName": "google.cloud.batch.v1alpha.BatchService.CreateJob", + "service": { + "fullName": "google.cloud.batch.v1alpha.BatchService", + "shortName": "BatchService" + }, + "shortName": "CreateJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1alpha.types.CreateJobRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "job", + "type": "google.cloud.batch_v1alpha.types.Job" + }, + { + "name": "job_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.batch_v1alpha.types.Job", + "shortName": "create_job" + }, + "description": "Sample for CreateJob", + "file": "batch_v1alpha_generated_batch_service_create_job_sync_ee80cfe8.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1alpha_generated_BatchService_CreateJob_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, { "end": 45, - "start": 42, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_create_job_sync.py" + "title": "batch_v1alpha_generated_batch_service_create_job_sync_ee80cfe8.py" }, { "canonical": true, @@ -207,7 +295,408 @@ "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.DeleteJobRequest" + "type": "google.cloud.batch_v1alpha.types.DeleteJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_job" + }, + "description": "Sample for DeleteJob", + "file": "batch_v1alpha_generated_batch_service_delete_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1alpha_generated_BatchService_DeleteJob_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1alpha_generated_batch_service_delete_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.delete_job", + "method": { + "fullName": "google.cloud.batch.v1alpha.BatchService.DeleteJob", + "service": { + "fullName": "google.cloud.batch.v1alpha.BatchService", + "shortName": "BatchService" + }, + "shortName": "DeleteJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1alpha.types.DeleteJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_job" + }, + "description": "Sample for DeleteJob", + "file": "batch_v1alpha_generated_batch_service_delete_job_sync_18fb9154.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1alpha_generated_BatchService_DeleteJob_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1alpha_generated_batch_service_delete_job_sync_18fb9154.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.delete_job", + "method": { + "fullName": "google.cloud.batch.v1alpha.BatchService.DeleteJob", + "service": { + "fullName": "google.cloud.batch.v1alpha.BatchService", + "shortName": "BatchService" + }, + "shortName": "DeleteJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1alpha.types.DeleteJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_job" + }, + "description": "Sample for DeleteJob", + "file": "batch_v1alpha_generated_batch_service_delete_job_sync_affefd11.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1alpha_generated_BatchService_DeleteJob_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1alpha_generated_batch_service_delete_job_sync_affefd11.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", + "shortName": "BatchServiceAsyncClient" + }, + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.get_job", + "method": { + "fullName": "google.cloud.batch.v1alpha.BatchService.GetJob", + "service": { + "fullName": "google.cloud.batch.v1alpha.BatchService", + "shortName": "BatchService" + }, + "shortName": "GetJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1alpha.types.GetJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.batch_v1alpha.types.Job", + "shortName": "get_job" + }, + "description": "Sample for GetJob", + "file": "batch_v1alpha_generated_batch_service_get_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1alpha_generated_BatchService_GetJob_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1alpha_generated_batch_service_get_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.get_job", + "method": { + "fullName": "google.cloud.batch.v1alpha.BatchService.GetJob", + "service": { + "fullName": "google.cloud.batch.v1alpha.BatchService", + "shortName": "BatchService" + }, + "shortName": "GetJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1alpha.types.GetJobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.batch_v1alpha.types.Job", + "shortName": "get_job" + }, + "description": "Sample for GetJob", + "file": "batch_v1alpha_generated_batch_service_get_job_sync_1014e8c7.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "batch_v1alpha_generated_BatchService_GetJob_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "batch_v1alpha_generated_batch_service_get_job_sync_1014e8c7.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" + }, + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.get_job", + "method": { + "fullName": "google.cloud.batch.v1alpha.BatchService.GetJob", + "service": { + "fullName": "google.cloud.batch.v1alpha.BatchService", + "shortName": "BatchService" + }, + "shortName": "GetJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.batch_v1alpha.types.GetJobRequest" }, { "name": "name", @@ -226,68 +715,69 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_job" + "resultType": "google.cloud.batch_v1alpha.types.Job", + "shortName": "get_job" }, - "description": "Sample for DeleteJob", - "file": "batch_v1alpha_generated_batch_service_delete_job_async.py", + "description": "Sample for GetJob", + "file": "batch_v1alpha_generated_batch_service_get_job_sync_17387e0a.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_DeleteJob_async", + "regionTag": "batch_v1alpha_generated_BatchService_GetJob_sync", "segments": [ { - "end": 47, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 38, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_delete_job_async.py" + "title": "batch_v1alpha_generated_batch_service_get_job_sync_17387e0a.py" }, { "canonical": true, "clientMethod": { + "async": true, "client": { - "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", - "shortName": "BatchServiceClient" + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", + "shortName": "BatchServiceAsyncClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.delete_job", + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.get_task", "method": { - "fullName": "google.cloud.batch.v1alpha.BatchService.DeleteJob", + "fullName": "google.cloud.batch.v1alpha.BatchService.GetTask", "service": { "fullName": "google.cloud.batch.v1alpha.BatchService", "shortName": "BatchService" }, - "shortName": "DeleteJob" + "shortName": "GetTask" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.DeleteJobRequest" + "type": "google.cloud.batch_v1alpha.types.GetTaskRequest" }, { "name": "name", @@ -306,69 +796,68 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_job" + "resultType": "google.cloud.batch_v1alpha.types.Task", + "shortName": "get_task" }, - "description": "Sample for DeleteJob", - "file": "batch_v1alpha_generated_batch_service_delete_job_sync.py", + "description": "Sample for GetTask", + "file": "batch_v1alpha_generated_batch_service_get_task_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_DeleteJob_sync", + "regionTag": "batch_v1alpha_generated_BatchService_GetTask_async", "segments": [ { - "end": 47, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 47, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 44, - "start": 38, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 48, - "start": 45, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_delete_job_sync.py" + "title": "batch_v1alpha_generated_batch_service_get_task_async.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", - "shortName": "BatchServiceAsyncClient" + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.get_job", + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.get_task", "method": { - "fullName": "google.cloud.batch.v1alpha.BatchService.GetJob", + "fullName": "google.cloud.batch.v1alpha.BatchService.GetTask", "service": { "fullName": "google.cloud.batch.v1alpha.BatchService", "shortName": "BatchService" }, - "shortName": "GetJob" + "shortName": "GetTask" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.GetJobRequest" + "type": "google.cloud.batch_v1alpha.types.GetTaskRequest" }, { "name": "name", @@ -387,47 +876,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.types.Job", - "shortName": "get_job" + "resultType": "google.cloud.batch_v1alpha.types.Task", + "shortName": "get_task" }, - "description": "Sample for GetJob", - "file": "batch_v1alpha_generated_batch_service_get_job_async.py", + "description": "Sample for GetTask", + "file": "batch_v1alpha_generated_batch_service_get_task_sync_29b69ea9.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_GetJob_async", + "regionTag": "batch_v1alpha_generated_BatchService_GetTask_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_get_job_async.py" + "title": "batch_v1alpha_generated_batch_service_get_task_sync_29b69ea9.py" }, { "canonical": true, @@ -436,19 +925,19 @@ "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.get_job", + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.get_task", "method": { - "fullName": "google.cloud.batch.v1alpha.BatchService.GetJob", + "fullName": "google.cloud.batch.v1alpha.BatchService.GetTask", "service": { "fullName": "google.cloud.batch.v1alpha.BatchService", "shortName": "BatchService" }, - "shortName": "GetJob" + "shortName": "GetTask" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.GetJobRequest" + "type": "google.cloud.batch_v1alpha.types.GetTaskRequest" }, { "name": "name", @@ -467,47 +956,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.types.Job", - "shortName": "get_job" + "resultType": "google.cloud.batch_v1alpha.types.Task", + "shortName": "get_task" }, - "description": "Sample for GetJob", - "file": "batch_v1alpha_generated_batch_service_get_job_sync.py", + "description": "Sample for GetTask", + "file": "batch_v1alpha_generated_batch_service_get_task_sync_657a0e4c.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_GetJob_sync", + "regionTag": "batch_v1alpha_generated_BatchService_GetTask_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_get_job_sync.py" + "title": "batch_v1alpha_generated_batch_service_get_task_sync_657a0e4c.py" }, { "canonical": true, @@ -517,22 +1006,22 @@ "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", "shortName": "BatchServiceAsyncClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.get_task", + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.list_jobs", "method": { - "fullName": "google.cloud.batch.v1alpha.BatchService.GetTask", + "fullName": "google.cloud.batch.v1alpha.BatchService.ListJobs", "service": { "fullName": "google.cloud.batch.v1alpha.BatchService", "shortName": "BatchService" }, - "shortName": "GetTask" + "shortName": "ListJobs" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.GetTaskRequest" + "type": "google.cloud.batch_v1alpha.types.ListJobsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -548,47 +1037,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.types.Task", - "shortName": "get_task" + "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListJobsAsyncPager", + "shortName": "list_jobs" }, - "description": "Sample for GetTask", - "file": "batch_v1alpha_generated_batch_service_get_task_async.py", + "description": "Sample for ListJobs", + "file": "batch_v1alpha_generated_batch_service_list_jobs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_GetTask_async", + "regionTag": "batch_v1alpha_generated_BatchService_ListJobs_async", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 44, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_get_task_async.py" + "title": "batch_v1alpha_generated_batch_service_list_jobs_async.py" }, { "canonical": true, @@ -597,22 +1086,22 @@ "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.get_task", + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.list_jobs", "method": { - "fullName": "google.cloud.batch.v1alpha.BatchService.GetTask", + "fullName": "google.cloud.batch.v1alpha.BatchService.ListJobs", "service": { "fullName": "google.cloud.batch.v1alpha.BatchService", "shortName": "BatchService" }, - "shortName": "GetTask" + "shortName": "ListJobs" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.GetTaskRequest" + "type": "google.cloud.batch_v1alpha.types.ListJobsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -628,57 +1117,56 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.types.Task", - "shortName": "get_task" + "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListJobsPager", + "shortName": "list_jobs" }, - "description": "Sample for GetTask", - "file": "batch_v1alpha_generated_batch_service_get_task_sync.py", + "description": "Sample for ListJobs", + "file": "batch_v1alpha_generated_batch_service_list_jobs_sync_21301b63.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_GetTask_sync", + "regionTag": "batch_v1alpha_generated_BatchService_ListJobs_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 44, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 42, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_get_task_sync.py" + "title": "batch_v1alpha_generated_batch_service_list_jobs_sync_21301b63.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", - "shortName": "BatchServiceAsyncClient" + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.list_jobs", + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.list_jobs", "method": { "fullName": "google.cloud.batch.v1alpha.BatchService.ListJobs", "service": { @@ -709,68 +1197,69 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListJobsAsyncPager", + "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListJobsPager", "shortName": "list_jobs" }, "description": "Sample for ListJobs", - "file": "batch_v1alpha_generated_batch_service_list_jobs_async.py", + "file": "batch_v1alpha_generated_batch_service_list_jobs_sync_830dac29.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_ListJobs_async", + "regionTag": "batch_v1alpha_generated_BatchService_ListJobs_sync", "segments": [ { - "end": 44, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 51, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 44, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 40, - "start": 38, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 41, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_list_jobs_async.py" + "title": "batch_v1alpha_generated_batch_service_list_jobs_sync_830dac29.py" }, { "canonical": true, "clientMethod": { + "async": true, "client": { - "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", - "shortName": "BatchServiceClient" + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", + "shortName": "BatchServiceAsyncClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.list_jobs", + "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.list_tasks", "method": { - "fullName": "google.cloud.batch.v1alpha.BatchService.ListJobs", + "fullName": "google.cloud.batch.v1alpha.BatchService.ListTasks", "service": { "fullName": "google.cloud.batch.v1alpha.BatchService", "shortName": "BatchService" }, - "shortName": "ListJobs" + "shortName": "ListTasks" }, "parameters": [ { "name": "request", - "type": "google.cloud.batch_v1alpha.types.ListJobsRequest" + "type": "google.cloud.batch_v1alpha.types.ListTasksRequest" }, { "name": "parent", @@ -789,57 +1278,56 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListJobsPager", - "shortName": "list_jobs" + "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListTasksAsyncPager", + "shortName": "list_tasks" }, - "description": "Sample for ListJobs", - "file": "batch_v1alpha_generated_batch_service_list_jobs_sync.py", + "description": "Sample for ListTasks", + "file": "batch_v1alpha_generated_batch_service_list_tasks_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_ListJobs_sync", + "regionTag": "batch_v1alpha_generated_BatchService_ListTasks_async", "segments": [ { - "end": 44, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 44, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 37, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 40, - "start": 38, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 45, - "start": 41, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_list_jobs_sync.py" + "title": "batch_v1alpha_generated_batch_service_list_tasks_async.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient", - "shortName": "BatchServiceAsyncClient" + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient", + "shortName": "BatchServiceClient" }, - "fullName": "google.cloud.batch_v1alpha.BatchServiceAsyncClient.list_tasks", + "fullName": "google.cloud.batch_v1alpha.BatchServiceClient.list_tasks", "method": { "fullName": "google.cloud.batch.v1alpha.BatchService.ListTasks", "service": { @@ -870,47 +1358,47 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListTasksAsyncPager", + "resultType": "google.cloud.batch_v1alpha.services.batch_service.pagers.ListTasksPager", "shortName": "list_tasks" }, "description": "Sample for ListTasks", - "file": "batch_v1alpha_generated_batch_service_list_tasks_async.py", + "file": "batch_v1alpha_generated_batch_service_list_tasks_sync_97ddc579.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "batch_v1alpha_generated_BatchService_ListTasks_async", + "regionTag": "batch_v1alpha_generated_BatchService_ListTasks_sync", "segments": [ { - "end": 45, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 45, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 46, - "start": 42, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_list_tasks_async.py" + "title": "batch_v1alpha_generated_batch_service_list_tasks_sync_97ddc579.py" }, { "canonical": true, @@ -954,43 +1442,43 @@ "shortName": "list_tasks" }, "description": "Sample for ListTasks", - "file": "batch_v1alpha_generated_batch_service_list_tasks_sync.py", + "file": "batch_v1alpha_generated_batch_service_list_tasks_sync_af95f032.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "batch_v1alpha_generated_BatchService_ListTasks_sync", "segments": [ { - "end": 45, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 45, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 33, - "start": 31, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 38, - "start": 34, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 41, - "start": 39, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 46, - "start": 42, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "batch_v1alpha_generated_batch_service_list_tasks_sync.py" + "title": "batch_v1alpha_generated_batch_service_list_tasks_sync_af95f032.py" } ] } diff --git a/samples/noxfile.py b/samples/noxfile.py new file mode 100644 index 0000000..b053ca5 --- /dev/null +++ b/samples/noxfile.py @@ -0,0 +1,313 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import print_function + +import glob +import os +from pathlib import Path +import sys +from typing import Callable, Dict, List, Optional + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +BLACK_VERSION = "black==22.3.0" +ISORT_VERSION = "isort==5.10.1" + +# Copy `noxfile_config.py` to your directory and modify it instead. + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + "ignored_versions": [], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": False, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append(".") + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars() -> Dict[str, str]: + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG["gcloud_project_env"] + # This should error out if not set. + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG["envs"]) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to test samples. +ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + +# +# Style Checks +# + + +def _determine_local_import_names(start_dir: str) -> List[str]: + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session: nox.sessions.Session) -> None: + if not TEST_CONFIG["enforce_type_hints"]: + session.install("flake8", "flake8-import-order") + else: + session.install("flake8", "flake8-import-order", "flake8-annotations") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + ".", + ] + session.run("flake8", *args) + + +# +# Black +# + + +@nox.session +def blacken(session: nox.sessions.Session) -> None: + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + session.run("black", *python_files) + + +# +# format = isort + black +# + + +@nox.session +def format(session: nox.sessions.Session) -> None: + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run("isort", "--fss", *python_files) + session.run("black", *python_files) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests( + session: nox.sessions.Session, post_install: Callable = None +) -> None: + # check for presence of tests + test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( + "**/test_*.py", recursive=True + ) + test_list.extend(glob.glob("**/tests", recursive=True)) + + if len(test_list) == 0: + print("No tests found, skipping directory.") + return + + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") + """Runs py.test for a particular project.""" + concurrent_args = [] + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + with open("requirements.txt") as rfile: + packages = rfile.read() + + if os.path.exists("requirements-test.txt"): + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") + with open("requirements-test.txt") as rtfile: + packages += rtfile.read() + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + if "pytest-parallel" in packages: + concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) + elif "pytest-xdist" in packages: + concurrent_args.extend(["-n", "auto"]) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session: nox.sessions.Session) -> None: + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) + + +# +# Readmegen +# + + +def _get_repo_root() -> Optional[str]: + """Returns the root folder of the project.""" + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + # .git is not available in repos cloned via Cloud Build + # setup.py is always in the library's root, so use that instead + # https://github.com/googleapis/synthtool/issues/792 + if Path(p / "setup.py").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session: nox.sessions.Session, path: str) -> None: + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/samples/noxfile_config.py b/samples/noxfile_config.py new file mode 100644 index 0000000..d27b90b --- /dev/null +++ b/samples/noxfile_config.py @@ -0,0 +1,17 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +TEST_CONFIG_OVERRIDE = { + "gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_PROJECT", +} diff --git a/samples/requirements-test.txt b/samples/requirements-test.txt new file mode 100644 index 0000000..75ceb43 --- /dev/null +++ b/samples/requirements-test.txt @@ -0,0 +1,2 @@ +pytest==7.1.3 +pytest-parallel==0.1.1 diff --git a/samples/requirements.txt b/samples/requirements.txt new file mode 100644 index 0000000..e88c9b0 --- /dev/null +++ b/samples/requirements.txt @@ -0,0 +1,3 @@ +isort==5.10.1 +black==22.8.0 +google-cloud-batch==0.2.0 diff --git a/samples/snippets/__init__.py b/samples/snippets/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/samples/snippets/create/__init__.py b/samples/snippets/create/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/samples/snippets/create/create_with_container_no_mounting.py b/samples/snippets/create/create_with_container_no_mounting.py new file mode 100644 index 0000000..9c54318 --- /dev/null +++ b/samples/snippets/create/create_with_container_no_mounting.py @@ -0,0 +1,86 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START batch_create_container_job] +from google.cloud import batch_v1 + + +def create_container_job(project_id: str, region: str, job_name: str) -> batch_v1.Job: + """ + This method shows how to create a sample Batch Job that will run + a simple command inside a container on Cloud Compute instances. + + Args: + project_id: project ID or project number of the Cloud project you want to use. + region: name of the region you want to use to run the job. Regions that are + available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations + job_name: the name of the job that will be created. + It needs to be unique for each project and region pair. + + Returns: + A job object representing the job created. + """ + client = batch_v1.BatchServiceClient() + + # Define what will be done as part of the job. + runnable = batch_v1.Runnable() + runnable.container = batch_v1.Runnable.Container() + runnable.container.image_uri = "gcr.io/google-containers/busybox" + runnable.container.entrypoint = "/bin/sh" + runnable.container.commands = ["-c", "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."] + + # Jobs can be divided into tasks. In this case, we have only one task. + task = batch_v1.TaskSpec() + task.runnables = [runnable] + + # We can specify what resources are requested by each task. + resources = batch_v1.ComputeResource() + resources.cpu_milli = 2000 # in milliseconds per cpu-second. This means the task requires 2 whole CPUs. + resources.memory_mib = 16 # in MiB + task.compute_resource = resources + + task.max_retry_count = 2 + task.max_run_duration = "3600s" + + # Tasks are grouped inside a job using TaskGroups. + group = batch_v1.TaskGroup() + group.task_count = 4 + group.task_spec = task + + # Policies are used to define on what kind of virtual machines the tasks will run on. + # In this case, we tell the system to use "e2-standard-4" machine type. + # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types + policy = batch_v1.AllocationPolicy.InstancePolicy() + policy.machine_type = "e2-standard-4" + instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate() + instances.policy = policy + allocation_policy = batch_v1.AllocationPolicy() + allocation_policy.instances = [instances] + + job = batch_v1.Job() + job.task_groups = [group] + job.allocation_policy = allocation_policy + job.labels = {"env": "testing", "type": "container"} + # We use Cloud Logging as it's an out of the box available option + job.logs_policy = batch_v1.LogsPolicy() + job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING + + create_request = batch_v1.CreateJobRequest() + create_request.job = job + create_request.job_id = job_name + # The job's parent is the region in which the job will run + create_request.parent = f"projects/{project_id}/locations/{region}" + + return client.create_job(create_request) +# [END batch_create_container_job] diff --git a/samples/snippets/create/create_with_script_no_mounting.py b/samples/snippets/create/create_with_script_no_mounting.py new file mode 100644 index 0000000..29942cb --- /dev/null +++ b/samples/snippets/create/create_with_script_no_mounting.py @@ -0,0 +1,86 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START batch_create_script_job] +from google.cloud import batch_v1 + + +def create_script_job(project_id: str, region: str, job_name: str) -> batch_v1.Job: + """ + This method shows how to create a sample Batch Job that will run + a simple command on Cloud Compute instances. + + Args: + project_id: project ID or project number of the Cloud project you want to use. + region: name of the region you want to use to run the job. Regions that are + available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations + job_name: the name of the job that will be created. + It needs to be unique for each project and region pair. + + Returns: + A job object representing the job created. + """ + client = batch_v1.BatchServiceClient() + + # Define what will be done as part of the job. + task = batch_v1.TaskSpec() + runnable = batch_v1.Runnable() + runnable.script = batch_v1.Runnable.Script() + runnable.script.text = "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks." + # You can also run a script from a file. Just remember, that needs to be a script that's + # already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually + # exclusive. + # runnable.script.path = '/tmp/test.sh' + task.runnables = [runnable] + + # We can specify what resources are requested by each task. + resources = batch_v1.ComputeResource() + resources.cpu_milli = 2000 # in milliseconds per cpu-second. This means the task requires 2 whole CPUs. + resources.memory_mib = 16 + task.compute_resource = resources + + task.max_retry_count = 2 + task.max_run_duration = "3600s" + + # Tasks are grouped inside a job using TaskGroups. + group = batch_v1.TaskGroup() + group.task_count = 4 + group.task_spec = task + + # Policies are used to define on what kind of virtual machines the tasks will run on. + # In this case, we tell the system to use "e2-standard-4" machine type. + # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types + allocation_policy = batch_v1.AllocationPolicy() + policy = batch_v1.AllocationPolicy.InstancePolicy() + policy.machine_type = "e2-standard-4" + instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate() + instances.policy = policy + allocation_policy.instances = [instances] + + job = batch_v1.Job() + job.task_groups = [group] + job.allocation_policy = allocation_policy + job.labels = {"env": "testing", "type": "script"} + # We use Cloud Logging as it's an out of the box available option + job.logs_policy = batch_v1.LogsPolicy() + job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING + + create_request = batch_v1.CreateJobRequest() + create_request.job = job + create_request.job_id = job_name + # The job's parent is the region in which the job will run + create_request.parent = f"projects/{project_id}/locations/{region}" + + return client.create_job(create_request) +# [END batch_create_script_job] diff --git a/samples/snippets/delete/delete_job.py b/samples/snippets/delete/delete_job.py new file mode 100644 index 0000000..f4ebdcd --- /dev/null +++ b/samples/snippets/delete/delete_job.py @@ -0,0 +1,37 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START batch_delete_job] +from google.api_core.operation import Operation + +from google.cloud import batch_v1 + + +def delete_job(project_id: str, region: str, job_name: str) -> Operation: + """ + Triggers the deletion of a Job. + + Args: + project_id: project ID or project number of the Cloud project you want to use. + region: name of the region hosts the job. + job_name: the name of the job that you want to delete. + + Returns: + An operation object related to the deletion. You can call `.result()` + on it to wait for its completion. + """ + client = batch_v1.BatchServiceClient() + + return client.delete_job(name=f"projects/{project_id}/locations/{region}/jobs/{job_name}") +# [END batch_delete_job] diff --git a/samples/snippets/get/get_job.py b/samples/snippets/get/get_job.py new file mode 100644 index 0000000..8dff737 --- /dev/null +++ b/samples/snippets/get/get_job.py @@ -0,0 +1,35 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# [START batch_get_job] + +from google.cloud import batch_v1 + + +def get_job(project_id: str, region: str, job_name: str) -> batch_v1.Job: + """ + Retrieve information about a Batch Job. + + Args: + project_id: project ID or project number of the Cloud project you want to use. + region: name of the region hosts the job. + job_name: the name of the job you want to retrieve information about. + + Returns: + A Job object representing the specified job. + """ + client = batch_v1.BatchServiceClient() + + return client.get_job(name=f"projects/{project_id}/locations/{region}/jobs/{job_name}") +# [END batch_get_job] diff --git a/samples/snippets/list/list_jobs.py b/samples/snippets/list/list_jobs.py new file mode 100644 index 0000000..77c39b5 --- /dev/null +++ b/samples/snippets/list/list_jobs.py @@ -0,0 +1,34 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Iterable + +# [START batch_list_jobs] +from google.cloud import batch_v1 + + +def list_jobs(project_id: str, region: str) -> Iterable[batch_v1.Job]: + """ + Get a list of all jobs defined in given region. + + Args: + project_id: project ID or project number of the Cloud project you want to use. + region: name of the region hosting the jobs. + + Returns: + An iterable collection of Job object. + """ + client = batch_v1.BatchServiceClient() + + return client.list_jobs(parent=f"projects/{project_id}/locations/{region}") +# [END batch_list_jobs] diff --git a/samples/snippets/tests/__init__.py b/samples/snippets/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/samples/snippets/tests/test_basics.py b/samples/snippets/tests/test_basics.py new file mode 100644 index 0000000..88dfa75 --- /dev/null +++ b/samples/snippets/tests/test_basics.py @@ -0,0 +1,79 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import time +import uuid + + +import google.auth +from google.cloud import batch_v1 +import pytest + +from ..create.create_with_container_no_mounting import create_container_job +from ..create.create_with_script_no_mounting import create_script_job + +from ..delete.delete_job import delete_job +from ..get.get_job import get_job +from ..list.list_jobs import list_jobs + +PROJECT = google.auth.default()[1] +REGION = 'europe-north1' + +TIMEOUT = 600 # 10 minutes + +WAIT_STATES = { + batch_v1.JobStatus.State.STATE_UNSPECIFIED, + batch_v1.JobStatus.State.QUEUED, + batch_v1.JobStatus.State.RUNNING, + batch_v1.JobStatus.State.SCHEDULED, +} + + +@pytest.fixture +def job_name(): + return f"test-job-{uuid.uuid4().hex[:10]}" + + +def _test_body(test_job: batch_v1.Job): + start_time = time.time() + try: + while test_job.status.state in WAIT_STATES: + if time.time() - start_time > TIMEOUT: + pytest.fail("Timed out while waiting for job to complete!") + test_job = get_job(PROJECT, REGION, test_job.name.rsplit('/', maxsplit=1)[1]) + time.sleep(5) + + assert test_job.status.state in (batch_v1.JobStatus.State.SUCCEEDED, + batch_v1.JobStatus.State.DELETION_IN_PROGRESS) + + for job in list_jobs(PROJECT, REGION): + if test_job.uid == job.uid: + break + else: + pytest.fail(f"Couldn't find job {test_job.uid} on the list of jobs.") + finally: + delete_job(PROJECT, REGION, test_job.name.rsplit('/', maxsplit=1)[1]).result() + + for job in list_jobs(PROJECT, REGION): + if job.uid == test_job.uid: + pytest.fail("The test job should be deleted at this point!") + + +def test_script_job(job_name): + job = create_script_job(PROJECT, REGION, job_name) + _test_body(job) + + +def test_container_job(job_name): + job = create_container_job(PROJECT, REGION, job_name) + _test_body(job) diff --git a/setup.py b/setup.py index 2eda0a0..b53521b 100644 --- a/setup.py +++ b/setup.py @@ -21,12 +21,12 @@ name = "google-cloud-batch" description = "Cloud Batch API client library" -version = "0.2.0" +version = "0.3.0" release_status = "Development Status :: 4 - Beta" dependencies = [ - "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "google-api-core[grpc] >= 1.33.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf >= 3.19.0, <5.0.0dev", + "protobuf >= 3.20.1, <5.0.0dev", "grpc-google-iam-v1 >=0.12.4, <1.0.0dev", ] url = "https://github.com/googleapis/python-batch" diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 461fa1f..1384af6 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -4,7 +4,7 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.32.0 +google-api-core==1.33.1 proto-plus==1.22.0 -protobuf==3.19.0 +protobuf==3.20.1 grpc-google-iam-v1==0.12.4 diff --git a/tests/unit/gapic/batch_v1/test_batch_service.py b/tests/unit/gapic/batch_v1/test_batch_service.py index 8853195..23479f0 100644 --- a/tests/unit/gapic/batch_v1/test_batch_service.py +++ b/tests/unit/gapic/batch_v1/test_batch_service.py @@ -18,16 +18,23 @@ # try/except added for compatibility with python < 3.8 try: from unittest import mock - from unittest.mock import AsyncMock -except ImportError: + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER import mock import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -107,6 +114,7 @@ def test__get_default_mtls_endpoint(): [ (BatchServiceClient, "grpc"), (BatchServiceAsyncClient, "grpc_asyncio"), + (BatchServiceClient, "rest"), ], ) def test_batch_service_client_from_service_account_info(client_class, transport_name): @@ -120,7 +128,11 @@ def test_batch_service_client_from_service_account_info(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("batch.googleapis.com:443") + assert client.transport._host == ( + "batch.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com" + ) @pytest.mark.parametrize( @@ -128,6 +140,7 @@ def test_batch_service_client_from_service_account_info(client_class, transport_ [ (transports.BatchServiceGrpcTransport, "grpc"), (transports.BatchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BatchServiceRestTransport, "rest"), ], ) def test_batch_service_client_service_account_always_use_jwt( @@ -153,6 +166,7 @@ def test_batch_service_client_service_account_always_use_jwt( [ (BatchServiceClient, "grpc"), (BatchServiceAsyncClient, "grpc_asyncio"), + (BatchServiceClient, "rest"), ], ) def test_batch_service_client_from_service_account_file(client_class, transport_name): @@ -173,13 +187,18 @@ def test_batch_service_client_from_service_account_file(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("batch.googleapis.com:443") + assert client.transport._host == ( + "batch.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com" + ) def test_batch_service_client_get_transport_class(): transport = BatchServiceClient.get_transport_class() available_transports = [ transports.BatchServiceGrpcTransport, + transports.BatchServiceRestTransport, ] assert transport in available_transports @@ -196,6 +215,7 @@ def test_batch_service_client_get_transport_class(): transports.BatchServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -339,6 +359,8 @@ def test_batch_service_client_client_options( "grpc_asyncio", "false", ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest", "true"), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -532,6 +554,7 @@ def test_batch_service_client_get_mtls_endpoint_and_cert_source(client_class): transports.BatchServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest"), ], ) def test_batch_service_client_client_options_scopes( @@ -572,6 +595,7 @@ def test_batch_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest", None), ], ) def test_batch_service_client_client_options_credentials_file( @@ -2476,756 +2500,3209 @@ async def test_list_tasks_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BatchServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + batch.CreateJobRequest, + dict, + ], +) +def test_create_job_rest(request_type): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BatchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["job"] = { + "name": "name_value", + "uid": "uid_value", + "priority": 898, + "task_groups": [ + { + "name": "name_value", + "task_spec": { + "runnables": [ + { + "container": { + "image_uri": "image_uri_value", + "commands": ["commands_value1", "commands_value2"], + "entrypoint": "entrypoint_value", + "volumes": ["volumes_value1", "volumes_value2"], + "options": "options_value", + "block_external_network": True, + "username": "username_value", + "password": "password_value", + }, + "script": {"path": "path_value", "text": "text_value"}, + "barrier": {"name": "name_value"}, + "ignore_exit_status": True, + "background": True, + "always_run": True, + "environment": {"variables": {}}, + "timeout": {"seconds": 751, "nanos": 543}, + } + ], + "compute_resource": { + "cpu_milli": 958, + "memory_mib": 1072, + "boot_disk_mib": 1365, + }, + "max_run_duration": {}, + "max_retry_count": 1635, + "lifecycle_policies": [ + {"action": 1, "action_condition": {"exit_codes": [1064, 1065]}} + ], + "environments": {}, + "volumes": [ + { + "nfs": { + "server": "server_value", + "remote_path": "remote_path_value", + }, + "gcs": {"remote_path": "remote_path_value"}, + "device_name": "device_name_value", + "mount_path": "mount_path_value", + "mount_options": [ + "mount_options_value1", + "mount_options_value2", + ], + } + ], + "environment": {}, + }, + "task_count": 1083, + "parallelism": 1174, + "task_environments": {}, + "task_count_per_node": 2022, + "require_hosts_file": True, + "permissive_ssh": True, + } + ], + "allocation_policy": { + "location": { + "allowed_locations": [ + "allowed_locations_value1", + "allowed_locations_value2", + ] + }, + "instances": [ + { + "policy": { + "machine_type": "machine_type_value", + "min_cpu_platform": "min_cpu_platform_value", + "provisioning_model": 1, + "accelerators": [ + { + "type_": "type__value", + "count": 553, + "install_gpu_drivers": True, + } + ], + "disks": [ + { + "new_disk": { + "image": "image_value", + "snapshot": "snapshot_value", + "type_": "type__value", + "size_gb": 739, + "disk_interface": "disk_interface_value", + }, + "existing_disk": "existing_disk_value", + "device_name": "device_name_value", + } + ], + }, + "instance_template": "instance_template_value", + } + ], + "labels": {}, + "network": { + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "no_external_ip_address": True, + } + ] + }, + }, + "labels": {}, + "status": { + "state": 1, + "status_events": [ + { + "type_": "type__value", + "description": "description_value", + "event_time": {"seconds": 751, "nanos": 543}, + "task_execution": {"exit_code": 948}, + } + ], + "task_groups": {}, + "run_duration": {}, + }, + "create_time": {}, + "update_time": {}, + "logs_policy": {"destination": 1, "logs_path": "logs_path_value"}, + "notifications": [ + { + "pubsub_topic": "pubsub_topic_value", + "message": {"type_": 1, "new_job_state": 1, "new_task_state": 1}, + } + ], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcb_job.Job( + name="name_value", + uid="uid_value", + priority=898, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BatchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcb_job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcb_job.Job) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.priority == 898 + + +def test_create_job_rest_required_fields(request_type=batch.CreateJobRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "job_id", + "request_id", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.BatchServiceGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcb_job.Job() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcb_job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_job(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_job_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + unset_fields = transport.create_job._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "jobId", + "requestId", + ) ) + & set( + ( + "parent", + "job", + ) + ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.BatchServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_job_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_create_job" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_create_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.CreateJobRequest.pb(batch.CreateJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcb_job.Job.to_json(gcb_job.Job()) + + request = batch.CreateJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcb_job.Job() + + client.create_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BatchServiceGrpcTransport( + +def test_create_job_rest_bad_request( + transport: str = "rest", request_type=batch.CreateJobRequest +): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = BatchServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["job"] = { + "name": "name_value", + "uid": "uid_value", + "priority": 898, + "task_groups": [ + { + "name": "name_value", + "task_spec": { + "runnables": [ + { + "container": { + "image_uri": "image_uri_value", + "commands": ["commands_value1", "commands_value2"], + "entrypoint": "entrypoint_value", + "volumes": ["volumes_value1", "volumes_value2"], + "options": "options_value", + "block_external_network": True, + "username": "username_value", + "password": "password_value", + }, + "script": {"path": "path_value", "text": "text_value"}, + "barrier": {"name": "name_value"}, + "ignore_exit_status": True, + "background": True, + "always_run": True, + "environment": {"variables": {}}, + "timeout": {"seconds": 751, "nanos": 543}, + } + ], + "compute_resource": { + "cpu_milli": 958, + "memory_mib": 1072, + "boot_disk_mib": 1365, + }, + "max_run_duration": {}, + "max_retry_count": 1635, + "lifecycle_policies": [ + {"action": 1, "action_condition": {"exit_codes": [1064, 1065]}} + ], + "environments": {}, + "volumes": [ + { + "nfs": { + "server": "server_value", + "remote_path": "remote_path_value", + }, + "gcs": {"remote_path": "remote_path_value"}, + "device_name": "device_name_value", + "mount_path": "mount_path_value", + "mount_options": [ + "mount_options_value1", + "mount_options_value2", + ], + } + ], + "environment": {}, + }, + "task_count": 1083, + "parallelism": 1174, + "task_environments": {}, + "task_count_per_node": 2022, + "require_hosts_file": True, + "permissive_ssh": True, + } + ], + "allocation_policy": { + "location": { + "allowed_locations": [ + "allowed_locations_value1", + "allowed_locations_value2", + ] + }, + "instances": [ + { + "policy": { + "machine_type": "machine_type_value", + "min_cpu_platform": "min_cpu_platform_value", + "provisioning_model": 1, + "accelerators": [ + { + "type_": "type__value", + "count": 553, + "install_gpu_drivers": True, + } + ], + "disks": [ + { + "new_disk": { + "image": "image_value", + "snapshot": "snapshot_value", + "type_": "type__value", + "size_gb": 739, + "disk_interface": "disk_interface_value", + }, + "existing_disk": "existing_disk_value", + "device_name": "device_name_value", + } + ], + }, + "instance_template": "instance_template_value", + } + ], + "labels": {}, + "network": { + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "no_external_ip_address": True, + } + ] + }, + }, + "labels": {}, + "status": { + "state": 1, + "status_events": [ + { + "type_": "type__value", + "description": "description_value", + "event_time": {"seconds": 751, "nanos": 543}, + "task_execution": {"exit_code": 948}, + } + ], + "task_groups": {}, + "run_duration": {}, + }, + "create_time": {}, + "update_time": {}, + "logs_policy": {"destination": 1, "logs_path": "logs_path_value"}, + "notifications": [ + { + "pubsub_topic": "pubsub_topic_value", + "message": {"type_": 1, "new_job_state": 1, "new_task_state": 1}, + } + ], + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BatchServiceGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_job(request) + + +def test_create_job_rest_flattened(): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.BatchServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcb_job.Job() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + job=gcb_job.Job(name="name_value"), + job_id="job_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcb_job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_job(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/jobs" % client.transport._host, + args[1], + ) + + +def test_create_job_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_job( + batch.CreateJobRequest(), + parent="parent_value", + job=gcb_job.Job(name="name_value"), + job_id="job_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BatchServiceGrpcTransport, - transports.BatchServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + +def test_create_job_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + batch.GetJobRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = BatchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_get_job_rest(request_type): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.BatchServiceGrpcTransport, + transport="rest", ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) -def test_batch_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BatchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = job.Job( + name="name_value", + uid="uid_value", + priority=898, ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_batch_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.batch_v1.services.batch_service.transports.BatchServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.BatchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_job(request) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_job", - "get_job", - "delete_job", - "list_jobs", - "get_task", - "list_tasks", - "set_iam_policy", - "get_iam_policy", - "test_iam_permissions", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.priority == 898 + + +def test_get_job_rest_required_fields(request_type=batch.GetJobRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # verify fields with default values are dropped - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" -def test_batch_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.batch_v1.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BatchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = job.Job() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_job(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_job_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_job_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_get_job" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_get_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.GetJobRequest.pb(batch.GetJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = job.Job.to_json(job.Job()) + + request = batch.GetJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = job.Job() + + client.get_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_batch_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.batch_v1.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BatchServiceTransport() - adc.assert_called_once() +def test_get_job_rest_bad_request( + transport: str = "rest", request_type=batch.GetJobRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_batch_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - BatchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_job(request) + + +def test_get_job_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = job.Job() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -@pytest.mark.parametrize( - "transport_class", - [ - transports.BatchServiceGrpcTransport, - transports.BatchServiceGrpcAsyncIOTransport, - ], -) -def test_batch_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + client.get_job(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/jobs/*}" % client.transport._host, + args[1], ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BatchServiceGrpcTransport, - transports.BatchServiceGrpcAsyncIOTransport, - ], -) -def test_batch_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +def test_get_job_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_job( + batch.GetJobRequest(), + name="name_value", + ) + + +def test_get_job_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_class,grpc_helpers", + "request_type", [ - (transports.BatchServiceGrpcTransport, grpc_helpers), - (transports.BatchServiceGrpcAsyncIOTransport, grpc_helpers_async), + batch.DeleteJobRequest, + dict, ], ) -def test_batch_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. +def test_delete_job_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_job(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_job_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BatchServiceRestInterceptor, "post_delete_job" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_delete_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.DeleteJobRequest.pb(batch.DeleteJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - create_channel.assert_called_with( - "batch.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="batch.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), + request = batch.DeleteJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), ], ) + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_job_rest_bad_request( + transport: str = "rest", request_type=batch.DeleteJobRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_job(request) + + +def test_delete_job_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_job(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/jobs/*}" % client.transport._host, + args[1], + ) + + +def test_delete_job_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_job( + batch.DeleteJobRequest(), + name="name_value", + ) + + +def test_delete_job_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + @pytest.mark.parametrize( - "transport_class", - [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], + "request_type", + [ + batch.ListJobsRequest, + dict, + ], ) -def test_batch_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() +def test_list_jobs_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListJobsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListJobsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListJobsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_jobs_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_list_jobs" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_list_jobs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.ListJobsRequest.pb(batch.ListJobsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = batch.ListJobsResponse.to_json( + batch.ListJobsResponse() + ) + + request = batch.ListJobsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = batch.ListJobsResponse() + + client.list_jobs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_jobs_rest_bad_request( + transport: str = "rest", request_type=batch.ListJobsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_jobs(request) + + +def test_list_jobs_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListJobsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListJobsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_jobs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/jobs" % client.transport._host, + args[1], + ) + + +def test_list_jobs_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_jobs( + batch.ListJobsRequest(), + parent="parent_value", + ) + + +def test_list_jobs_rest_pager(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + batch.ListJobsResponse( + jobs=[ + job.Job(), + job.Job(), + job.Job(), + ], + next_page_token="abc", + ), + batch.ListJobsResponse( + jobs=[], + next_page_token="def", + ), + batch.ListJobsResponse( + jobs=[ + job.Job(), + ], + next_page_token="ghi", + ), + batch.ListJobsResponse( + jobs=[ + job.Job(), + job.Job(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(batch.ListJobsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, job.Job) for i in results) + + pages = list(client.list_jobs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + batch.GetTaskRequest, + dict, + ], +) +def test_get_task_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4/tasks/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = task.Task( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_task(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, task.Task) + assert response.name == "name_value" + + +def test_get_task_rest_required_fields(request_type=batch.GetTaskRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_task._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_task._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = task.Task() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_task(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_task_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_task._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_task_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_get_task" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_get_task" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.GetTaskRequest.pb(batch.GetTaskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = task.Task.to_json(task.Task()) + + request = batch.GetTaskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = task.Task() + + client.get_task( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_task_rest_bad_request( + transport: str = "rest", request_type=batch.GetTaskRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4/tasks/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_task(request) + + +def test_get_task_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = task.Task() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4/tasks/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_task(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/jobs/*/taskGroups/*/tasks/*}" + % client.transport._host, + args[1], + ) + + +def test_get_task_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_task( + batch.GetTaskRequest(), + name="name_value", + ) + + +def test_get_task_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + batch.ListTasksRequest, + dict, + ], +) +def test_list_tasks_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListTasksResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tasks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_tasks_rest_required_fields(request_type=batch.ListTasksRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tasks._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tasks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = batch.ListTasksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = batch.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_tasks(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tasks_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tasks._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tasks_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_list_tasks" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_list_tasks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.ListTasksRequest.pb(batch.ListTasksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = batch.ListTasksResponse.to_json( + batch.ListTasksResponse() + ) + + request = batch.ListTasksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = batch.ListTasksResponse() + + client.list_tasks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tasks_rest_bad_request( + transport: str = "rest", request_type=batch.ListTasksRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tasks(request) + + +def test_list_tasks_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListTasksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_tasks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/jobs/*/taskGroups/*}/tasks" + % client.transport._host, + args[1], + ) + + +def test_list_tasks_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_tasks( + batch.ListTasksRequest(), + parent="parent_value", + ) + + +def test_list_tasks_rest_pager(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + batch.ListTasksResponse( + tasks=[ + task.Task(), + task.Task(), + task.Task(), + ], + next_page_token="abc", + ), + batch.ListTasksResponse( + tasks=[], + next_page_token="def", + ), + batch.ListTasksResponse( + tasks=[ + task.Task(), + ], + next_page_token="ghi", + ), + batch.ListTasksResponse( + tasks=[ + task.Task(), + task.Task(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(batch.ListTasksResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + + pager = client.list_tasks(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, task.Task) for i in results) + + pages = list(client.list_tasks(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BatchServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BatchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BatchServiceGrpcTransport, + transports.BatchServiceGrpcAsyncIOTransport, + transports.BatchServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = BatchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BatchServiceGrpcTransport, + ) + + +def test_batch_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BatchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_batch_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.batch_v1.services.batch_service.transports.BatchServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BatchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_job", + "get_job", + "delete_job", + "list_jobs", + "get_task", + "list_tasks", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_batch_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.batch_v1.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BatchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_batch_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.batch_v1.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BatchServiceTransport() + adc.assert_called_once() + + +def test_batch_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + BatchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BatchServiceGrpcTransport, + transports.BatchServiceGrpcAsyncIOTransport, + ], +) +def test_batch_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BatchServiceGrpcTransport, + transports.BatchServiceGrpcAsyncIOTransport, + transports.BatchServiceRestTransport, + ], +) +def test_batch_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.BatchServiceGrpcTransport, grpc_helpers), + (transports.BatchServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_batch_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "batch.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="batch.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], +) +def test_batch_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( certificate_chain=expected_cert, private_key=expected_key ) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_batch_service_host_no_port(transport_name): +def test_batch_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.BatchServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_batch_service_rest_lro_client(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_batch_service_host_no_port(transport_name): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="batch.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "batch.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_batch_service_host_with_port(transport_name): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="batch.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "batch.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_batch_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BatchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BatchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_job._session + session2 = client2.transport.create_job._session + assert session1 != session2 + session1 = client1.transport.get_job._session + session2 = client2.transport.get_job._session + assert session1 != session2 + session1 = client1.transport.delete_job._session + session2 = client2.transport.delete_job._session + assert session1 != session2 + session1 = client1.transport.list_jobs._session + session2 = client2.transport.list_jobs._session + assert session1 != session2 + session1 = client1.transport.get_task._session + session2 = client2.transport.get_task._session + assert session1 != session2 + session1 = client1.transport.list_tasks._session + session2 = client2.transport.list_tasks._session + assert session1 != session2 + + +def test_batch_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BatchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_batch_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BatchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], +) +def test_batch_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], +) +def test_batch_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_batch_service_grpc_lro_client(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_batch_service_grpc_lro_async_client(): + client = BatchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_job_path(): + project = "squid" + location = "clam" + job = "whelk" + expected = "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) + actual = BatchServiceClient.job_path(project, location, job) + assert expected == actual + + +def test_parse_job_path(): + expected = { + "project": "octopus", + "location": "oyster", + "job": "nudibranch", + } + path = BatchServiceClient.job_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_job_path(path) + assert expected == actual + + +def test_task_path(): + project = "cuttlefish" + location = "mussel" + job = "winkle" + task_group = "nautilus" + task = "scallop" + expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}/tasks/{task}".format( + project=project, + location=location, + job=job, + task_group=task_group, + task=task, + ) + actual = BatchServiceClient.task_path(project, location, job, task_group, task) + assert expected == actual + + +def test_parse_task_path(): + expected = { + "project": "abalone", + "location": "squid", + "job": "clam", + "task_group": "whelk", + "task": "octopus", + } + path = BatchServiceClient.task_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_task_path(path) + assert expected == actual + + +def test_task_group_path(): + project = "oyster" + location = "nudibranch" + job = "cuttlefish" + task_group = "mussel" + expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}".format( + project=project, + location=location, + job=job, + task_group=task_group, + ) + actual = BatchServiceClient.task_group_path(project, location, job, task_group) + assert expected == actual + + +def test_parse_task_group_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "job": "scallop", + "task_group": "abalone", + } + path = BatchServiceClient.task_group_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_task_group_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = BatchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = BatchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = BatchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = BatchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = BatchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = BatchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = BatchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = BatchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.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, + ) + actual = BatchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = BatchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.BatchServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.BatchServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = BatchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = BatchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="batch.googleapis.com" - ), - transport=transport_name, + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) - assert client.transport._host == ("batch.googleapis.com:443") + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + locations_pb2.GetLocationRequest, + dict, ], ) -def test_batch_service_host_with_port(transport_name): +def test_get_location_rest(request_type): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="batch.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("batch.googleapis.com:8000") + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_batch_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that channel is used if provided. - transport = transports.BatchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + response = client.get_location(request) + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_batch_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.BatchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, +def test_list_locations_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", - [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], ) -def test_batch_service_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +def test_list_locations_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/jobs/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", - [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], ) -def test_batch_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() +def test_get_iam_policy_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - 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, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) -def test_batch_service_grpc_lro_client(): + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/jobs/sample3"}, request ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) -def test_batch_service_grpc_lro_async_client(): - client = BatchServiceAsyncClient( +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - transport = client.transport + request_init = {"resource": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) -def test_job_path(): - project = "squid" - location = "clam" - job = "whelk" - expected = "projects/{project}/locations/{location}/jobs/{job}".format( - project=project, - location=location, - job=job, - ) - actual = BatchServiceClient.job_path(project, location, job) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) -def test_parse_job_path(): - expected = { - "project": "octopus", - "location": "oyster", - "job": "nudibranch", - } - path = BatchServiceClient.job_path(**expected) +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/jobs/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_job_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) -def test_task_path(): - project = "cuttlefish" - location = "mussel" - job = "winkle" - task_group = "nautilus" - task = "scallop" - expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}/tasks/{task}".format( - project=project, - location=location, - job=job, - task_group=task_group, - task=task, +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.task_path(project, location, job, task_group, task) - assert expected == actual + request_init = {"resource": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_parse_task_path(): - expected = { - "project": "abalone", - "location": "squid", - "job": "clam", - "task_group": "whelk", - "task": "octopus", - } - path = BatchServiceClient.task_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_task_path(path) - assert expected == actual + response = client.test_iam_permissions(request) + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_task_group_path(): - project = "oyster" - location = "nudibranch" - job = "cuttlefish" - task_group = "mussel" - expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}".format( - project=project, - location=location, - job=job, - task_group=task_group, - ) - actual = BatchServiceClient.task_group_path(project, location, job, task_group) - assert expected == actual +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_task_group_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "job": "scallop", - "task_group": "abalone", - } - path = BatchServiceClient.task_group_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_task_group_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.common_billing_account_path(billing_account) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = BatchServiceClient.common_billing_account_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_billing_account_path(path) - assert expected == actual + response = client.cancel_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = BatchServiceClient.common_folder_path(folder) - assert expected == actual +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = BatchServiceClient.common_folder_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_folder_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.common_organization_path(organization) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = BatchServiceClient.common_organization_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_organization_path(path) - assert expected == actual + response = client.delete_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) - actual = BatchServiceClient.common_project_path(project) - assert expected == actual +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = BatchServiceClient.common_project_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_project_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.common_location_path(project, location) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = BatchServiceClient.common_location_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_location_path(path) - assert expected == actual + response = client.get_operation(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.BatchServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = BatchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - with mock.patch.object( - transports.BatchServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = BatchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = BatchServiceAsyncClient( + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) def test_delete_operation(transport: str = "grpc"): @@ -4592,6 +7069,7 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4609,6 +7087,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/batch_v1alpha/test_batch_service.py b/tests/unit/gapic/batch_v1alpha/test_batch_service.py index b2e1934..0ba1ce6 100644 --- a/tests/unit/gapic/batch_v1alpha/test_batch_service.py +++ b/tests/unit/gapic/batch_v1alpha/test_batch_service.py @@ -18,16 +18,23 @@ # try/except added for compatibility with python < 3.8 try: from unittest import mock - from unittest.mock import AsyncMock -except ImportError: + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER import mock import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api_core import client_options from google.api_core import exceptions as core_exceptions @@ -107,6 +114,7 @@ def test__get_default_mtls_endpoint(): [ (BatchServiceClient, "grpc"), (BatchServiceAsyncClient, "grpc_asyncio"), + (BatchServiceClient, "rest"), ], ) def test_batch_service_client_from_service_account_info(client_class, transport_name): @@ -120,7 +128,11 @@ def test_batch_service_client_from_service_account_info(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("batch.googleapis.com:443") + assert client.transport._host == ( + "batch.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com" + ) @pytest.mark.parametrize( @@ -128,6 +140,7 @@ def test_batch_service_client_from_service_account_info(client_class, transport_ [ (transports.BatchServiceGrpcTransport, "grpc"), (transports.BatchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BatchServiceRestTransport, "rest"), ], ) def test_batch_service_client_service_account_always_use_jwt( @@ -153,6 +166,7 @@ def test_batch_service_client_service_account_always_use_jwt( [ (BatchServiceClient, "grpc"), (BatchServiceAsyncClient, "grpc_asyncio"), + (BatchServiceClient, "rest"), ], ) def test_batch_service_client_from_service_account_file(client_class, transport_name): @@ -173,13 +187,18 @@ def test_batch_service_client_from_service_account_file(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("batch.googleapis.com:443") + assert client.transport._host == ( + "batch.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com" + ) def test_batch_service_client_get_transport_class(): transport = BatchServiceClient.get_transport_class() available_transports = [ transports.BatchServiceGrpcTransport, + transports.BatchServiceRestTransport, ] assert transport in available_transports @@ -196,6 +215,7 @@ def test_batch_service_client_get_transport_class(): transports.BatchServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -339,6 +359,8 @@ def test_batch_service_client_client_options( "grpc_asyncio", "false", ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest", "true"), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -532,6 +554,7 @@ def test_batch_service_client_get_mtls_endpoint_and_cert_source(client_class): transports.BatchServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest"), ], ) def test_batch_service_client_client_options_scopes( @@ -572,6 +595,7 @@ def test_batch_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (BatchServiceClient, transports.BatchServiceRestTransport, "rest", None), ], ) def test_batch_service_client_client_options_credentials_file( @@ -2488,756 +2512,3291 @@ async def test_list_tasks_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BatchServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + batch.CreateJobRequest, + dict, + ], +) +def test_create_job_rest(request_type): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BatchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["job"] = { + "name": "name_value", + "uid": "uid_value", + "priority": 898, + "task_groups": [ + { + "name": "name_value", + "task_spec": { + "runnables": [ + { + "container": { + "image_uri": "image_uri_value", + "commands": ["commands_value1", "commands_value2"], + "entrypoint": "entrypoint_value", + "volumes": ["volumes_value1", "volumes_value2"], + "options": "options_value", + "block_external_network": True, + "username": "username_value", + "password": "password_value", + }, + "script": {"path": "path_value", "text": "text_value"}, + "barrier": {"name": "name_value"}, + "ignore_exit_status": True, + "background": True, + "always_run": True, + "environment": { + "variables": {}, + "secret_variables": {}, + "encrypted_variables": { + "key_name": "key_name_value", + "cipher_text": "cipher_text_value", + }, + }, + "timeout": {"seconds": 751, "nanos": 543}, + "labels": {}, + } + ], + "compute_resource": { + "cpu_milli": 958, + "memory_mib": 1072, + "gpu_count": 980, + "boot_disk_mib": 1365, + }, + "max_run_duration": {}, + "max_retry_count": 1635, + "lifecycle_policies": [ + {"action": 1, "action_condition": {"exit_codes": [1064, 1065]}} + ], + "environments": {}, + "volumes": [ + { + "nfs": { + "server": "server_value", + "remote_path": "remote_path_value", + }, + "pd": { + "disk": "disk_value", + "device": "device_value", + "existing": True, + }, + "gcs": {"remote_path": "remote_path_value"}, + "device_name": "device_name_value", + "mount_path": "mount_path_value", + "mount_options": [ + "mount_options_value1", + "mount_options_value2", + ], + } + ], + "environment": {}, + }, + "task_count": 1083, + "parallelism": 1174, + "scheduling_policy": 1, + "allocation_policy": { + "location": { + "allowed_locations": [ + "allowed_locations_value1", + "allowed_locations_value2", + ], + "denied_locations": [ + "denied_locations_value1", + "denied_locations_value2", + ], + }, + "instance": { + "allowed_machine_types": [ + "allowed_machine_types_value1", + "allowed_machine_types_value2", + ], + "machine_type": "machine_type_value", + "min_cpu_platform": "min_cpu_platform_value", + "provisioning_model": 1, + "accelerators": [ + { + "type_": "type__value", + "count": 553, + "install_gpu_drivers": True, + } + ], + "disks": [ + { + "new_disk": { + "image": "image_value", + "snapshot": "snapshot_value", + "type_": "type__value", + "size_gb": 739, + "disk_interface": "disk_interface_value", + }, + "existing_disk": "existing_disk_value", + "device_name": "device_name_value", + } + ], + }, + "instances": [ + { + "policy": {}, + "instance_template": "instance_template_value", + "install_gpu_drivers": True, + } + ], + "instance_templates": [ + "instance_templates_value1", + "instance_templates_value2", + ], + "provisioning_models": [1], + "service_account_email": "service_account_email_value", + "service_account": { + "email": "email_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "labels": {}, + "network": { + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "no_external_ip_address": True, + } + ] + }, + }, + "labels": {}, + "task_environments": {}, + "task_count_per_node": 2022, + "require_hosts_file": True, + "permissive_ssh": True, + } + ], + "scheduling_policy": 1, + "dependencies": [{"items": {}}], + "allocation_policy": {}, + "labels": {}, + "status": { + "state": 1, + "status_events": [ + { + "type_": "type__value", + "description": "description_value", + "event_time": {"seconds": 751, "nanos": 543}, + "task_execution": {"exit_code": 948}, + } + ], + "task_groups": {}, + "run_duration": {}, + }, + "notification": { + "pubsub_topic": "pubsub_topic_value", + "message": {"type_": 1, "new_job_state": 1, "new_task_state": 1}, + }, + "create_time": {}, + "update_time": {}, + "logs_policy": {"destination": 1, "logs_path": "logs_path_value"}, + "notifications": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcb_job.Job( + name="name_value", + uid="uid_value", + priority=898, + scheduling_policy=gcb_job.Job.SchedulingPolicy.AS_SOON_AS_POSSIBLE, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BatchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcb_job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcb_job.Job) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.priority == 898 + assert ( + response.scheduling_policy == gcb_job.Job.SchedulingPolicy.AS_SOON_AS_POSSIBLE ) - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + +def test_create_job_rest_required_fields(request_type=batch.CreateJobRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "job_id", + "request_id", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.BatchServiceGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcb_job.Job() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcb_job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_job(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_job_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + unset_fields = transport.create_job._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "jobId", + "requestId", + ) + ) + & set( + ( + "parent", + "job", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.BatchServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_job_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = BatchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_create_job" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_create_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.CreateJobRequest.pb(batch.CreateJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcb_job.Job.to_json(gcb_job.Job()) + + request = batch.CreateJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcb_job.Job() + + client.create_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BatchServiceGrpcTransport( + +def test_create_job_rest_bad_request( + transport: str = "rest", request_type=batch.CreateJobRequest +): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = BatchServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["job"] = { + "name": "name_value", + "uid": "uid_value", + "priority": 898, + "task_groups": [ + { + "name": "name_value", + "task_spec": { + "runnables": [ + { + "container": { + "image_uri": "image_uri_value", + "commands": ["commands_value1", "commands_value2"], + "entrypoint": "entrypoint_value", + "volumes": ["volumes_value1", "volumes_value2"], + "options": "options_value", + "block_external_network": True, + "username": "username_value", + "password": "password_value", + }, + "script": {"path": "path_value", "text": "text_value"}, + "barrier": {"name": "name_value"}, + "ignore_exit_status": True, + "background": True, + "always_run": True, + "environment": { + "variables": {}, + "secret_variables": {}, + "encrypted_variables": { + "key_name": "key_name_value", + "cipher_text": "cipher_text_value", + }, + }, + "timeout": {"seconds": 751, "nanos": 543}, + "labels": {}, + } + ], + "compute_resource": { + "cpu_milli": 958, + "memory_mib": 1072, + "gpu_count": 980, + "boot_disk_mib": 1365, + }, + "max_run_duration": {}, + "max_retry_count": 1635, + "lifecycle_policies": [ + {"action": 1, "action_condition": {"exit_codes": [1064, 1065]}} + ], + "environments": {}, + "volumes": [ + { + "nfs": { + "server": "server_value", + "remote_path": "remote_path_value", + }, + "pd": { + "disk": "disk_value", + "device": "device_value", + "existing": True, + }, + "gcs": {"remote_path": "remote_path_value"}, + "device_name": "device_name_value", + "mount_path": "mount_path_value", + "mount_options": [ + "mount_options_value1", + "mount_options_value2", + ], + } + ], + "environment": {}, + }, + "task_count": 1083, + "parallelism": 1174, + "scheduling_policy": 1, + "allocation_policy": { + "location": { + "allowed_locations": [ + "allowed_locations_value1", + "allowed_locations_value2", + ], + "denied_locations": [ + "denied_locations_value1", + "denied_locations_value2", + ], + }, + "instance": { + "allowed_machine_types": [ + "allowed_machine_types_value1", + "allowed_machine_types_value2", + ], + "machine_type": "machine_type_value", + "min_cpu_platform": "min_cpu_platform_value", + "provisioning_model": 1, + "accelerators": [ + { + "type_": "type__value", + "count": 553, + "install_gpu_drivers": True, + } + ], + "disks": [ + { + "new_disk": { + "image": "image_value", + "snapshot": "snapshot_value", + "type_": "type__value", + "size_gb": 739, + "disk_interface": "disk_interface_value", + }, + "existing_disk": "existing_disk_value", + "device_name": "device_name_value", + } + ], + }, + "instances": [ + { + "policy": {}, + "instance_template": "instance_template_value", + "install_gpu_drivers": True, + } + ], + "instance_templates": [ + "instance_templates_value1", + "instance_templates_value2", + ], + "provisioning_models": [1], + "service_account_email": "service_account_email_value", + "service_account": { + "email": "email_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "labels": {}, + "network": { + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "no_external_ip_address": True, + } + ] + }, + }, + "labels": {}, + "task_environments": {}, + "task_count_per_node": 2022, + "require_hosts_file": True, + "permissive_ssh": True, + } + ], + "scheduling_policy": 1, + "dependencies": [{"items": {}}], + "allocation_policy": {}, + "labels": {}, + "status": { + "state": 1, + "status_events": [ + { + "type_": "type__value", + "description": "description_value", + "event_time": {"seconds": 751, "nanos": 543}, + "task_execution": {"exit_code": 948}, + } + ], + "task_groups": {}, + "run_duration": {}, + }, + "notification": { + "pubsub_topic": "pubsub_topic_value", + "message": {"type_": 1, "new_job_state": 1, "new_task_state": 1}, + }, + "create_time": {}, + "update_time": {}, + "logs_policy": {"destination": 1, "logs_path": "logs_path_value"}, + "notifications": {}, + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BatchServiceGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_job(request) + + +def test_create_job_rest_flattened(): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.BatchServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcb_job.Job() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + job=gcb_job.Job(name="name_value"), + job_id="job_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcb_job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_job(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/jobs" % client.transport._host, + args[1], + ) + + +def test_create_job_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_job( + batch.CreateJobRequest(), + parent="parent_value", + job=gcb_job.Job(name="name_value"), + job_id="job_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BatchServiceGrpcTransport, - transports.BatchServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + +def test_create_job_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + batch.GetJobRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = BatchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_get_job_rest(request_type): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.BatchServiceGrpcTransport, + transport="rest", ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) -def test_batch_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BatchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = job.Job( + name="name_value", + uid="uid_value", + priority=898, + scheduling_policy=job.Job.SchedulingPolicy.AS_SOON_AS_POSSIBLE, ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_batch_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.batch_v1alpha.services.batch_service.transports.BatchServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.BatchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_job(request) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_job", - "get_job", - "delete_job", - "list_jobs", - "get_task", - "list_tasks", - "set_iam_policy", - "get_iam_policy", - "test_iam_permissions", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.priority == 898 + assert response.scheduling_policy == job.Job.SchedulingPolicy.AS_SOON_AS_POSSIBLE + + +def test_get_job_rest_required_fields(request_type=batch.GetJobRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # verify fields with default values are dropped - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" -def test_batch_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.batch_v1alpha.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BatchServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = job.Job() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_job(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_job_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_job_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_get_job" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_get_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.GetJobRequest.pb(batch.GetJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = job.Job.to_json(job.Job()) + + request = batch.GetJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = job.Job() + + client.get_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_job_rest_bad_request( + transport: str = "rest", request_type=batch.GetJobRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_job(request) + + +def test_get_job_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = job.Job() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_batch_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.batch_v1alpha.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BatchServiceTransport() - adc.assert_called_once() + client.get_job(**mock_args) + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/jobs/*}" % client.transport._host, + args[1], + ) -def test_batch_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - BatchServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, + +def test_get_job_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_job( + batch.GetJobRequest(), + name="name_value", ) +def test_get_job_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.BatchServiceGrpcTransport, - transports.BatchServiceGrpcAsyncIOTransport, + batch.DeleteJobRequest, + dict, ], ) -def test_batch_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", +def test_delete_job_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_job(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_job_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BatchServiceRestInterceptor, "post_delete_job" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_delete_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.DeleteJobRequest.pb(batch.DeleteJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) + request = batch.DeleteJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() -@pytest.mark.parametrize( - "transport_class", - [ - transports.BatchServiceGrpcTransport, - transports.BatchServiceGrpcAsyncIOTransport, - ], -) -def test_batch_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + client.delete_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_job_rest_bad_request( + transport: str = "rest", request_type=batch.DeleteJobRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_job(request) + + +def test_delete_job_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/jobs/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_job(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/jobs/*}" % client.transport._host, + args[1], + ) + + +def test_delete_job_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_job( + batch.DeleteJobRequest(), + name="name_value", + ) + + +def test_delete_job_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_class,grpc_helpers", + "request_type", [ - (transports.BatchServiceGrpcTransport, grpc_helpers), - (transports.BatchServiceGrpcAsyncIOTransport, grpc_helpers_async), + batch.ListJobsRequest, + dict, ], ) -def test_batch_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. +def test_list_jobs_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListJobsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListJobsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListJobsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_jobs_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_list_jobs" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_list_jobs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.ListJobsRequest.pb(batch.ListJobsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = batch.ListJobsResponse.to_json( + batch.ListJobsResponse() + ) - create_channel.assert_called_with( - "batch.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="batch.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), + request = batch.ListJobsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = batch.ListJobsResponse() + + client.list_jobs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), ], ) + pre.assert_called_once() + post.assert_called_once() -@pytest.mark.parametrize( - "transport_class", - [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], -) -def test_batch_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), +def test_list_jobs_rest_bad_request( + transport: str = "rest", request_type=batch.ListJobsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_jobs(request) + + +def test_list_jobs_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListJobsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListJobsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_jobs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/jobs" % client.transport._host, + args[1], + ) + + +def test_list_jobs_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_jobs( + batch.ListJobsRequest(), + parent="parent_value", + ) + + +def test_list_jobs_rest_pager(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + batch.ListJobsResponse( + jobs=[ + job.Job(), + job.Job(), + job.Job(), + ], + next_page_token="abc", + ), + batch.ListJobsResponse( + jobs=[], + next_page_token="def", + ), + batch.ListJobsResponse( + jobs=[ + job.Job(), + ], + next_page_token="ghi", + ), + batch.ListJobsResponse( + jobs=[ + job.Job(), + job.Job(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(batch.ListJobsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, job.Job) for i in results) + + pages = list(client.list_jobs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + batch.GetTaskRequest, + dict, + ], +) +def test_get_task_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4/tasks/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = task.Task( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_task(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, task.Task) + assert response.name == "name_value" + + +def test_get_task_rest_required_fields(request_type=batch.GetTaskRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_task._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_task._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = task.Task() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_task(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_task_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_task._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_task_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_get_task" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_get_task" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.GetTaskRequest.pb(batch.GetTaskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = task.Task.to_json(task.Task()) + + request = batch.GetTaskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = task.Task() + + client.get_task( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), ], ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + pre.assert_called_once() + post.assert_called_once() + + +def test_get_task_rest_bad_request( + transport: str = "rest", request_type=batch.GetTaskRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4/tasks/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_task(request) + + +def test_get_task_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = task.Task() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4/tasks/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_task(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/jobs/*/taskGroups/*/tasks/*}" + % client.transport._host, + args[1], + ) + + +def test_get_task_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_task( + batch.GetTaskRequest(), + name="name_value", + ) + + +def test_get_task_rest_error(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + batch.ListTasksRequest, + dict, + ], +) +def test_list_tasks_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListTasksResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tasks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_tasks_rest_required_fields(request_type=batch.ListTasksRequest): + transport_class = transports.BatchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tasks._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tasks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = batch.ListTasksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = batch.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_tasks(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tasks_rest_unset_required_fields(): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tasks._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tasks_rest_interceptors(null_interceptor): + transport = transports.BatchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BatchServiceRestInterceptor(), + ) + client = BatchServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BatchServiceRestInterceptor, "post_list_tasks" + ) as post, mock.patch.object( + transports.BatchServiceRestInterceptor, "pre_list_tasks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = batch.ListTasksRequest.pb(batch.ListTasksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = batch.ListTasksResponse.to_json( + batch.ListTasksResponse() + ) + + request = batch.ListTasksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = batch.ListTasksResponse() + + client.list_tasks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tasks_rest_bad_request( + transport: str = "rest", request_type=batch.ListTasksRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tasks(request) + + +def test_list_tasks_rest_flattened(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = batch.ListTasksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = batch.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_tasks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*/jobs/*/taskGroups/*}/tasks" + % client.transport._host, + args[1], + ) + + +def test_list_tasks_rest_flattened_error(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_tasks( + batch.ListTasksRequest(), + parent="parent_value", + ) + + +def test_list_tasks_rest_pager(transport: str = "rest"): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + batch.ListTasksResponse( + tasks=[ + task.Task(), + task.Task(), + task.Task(), + ], + next_page_token="abc", + ), + batch.ListTasksResponse( + tasks=[], + next_page_token="def", + ), + batch.ListTasksResponse( + tasks=[ + task.Task(), + ], + next_page_token="ghi", + ), + batch.ListTasksResponse( + tasks=[ + task.Task(), + task.Task(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(batch.ListTasksResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/taskGroups/sample4" + } + + pager = client.list_tasks(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, task.Task) for i in results) + + pages = list(client.list_tasks(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BatchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BatchServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BatchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BatchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BatchServiceGrpcTransport, + transports.BatchServiceGrpcAsyncIOTransport, + transports.BatchServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = BatchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BatchServiceGrpcTransport, + ) + + +def test_batch_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BatchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_batch_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.batch_v1alpha.services.batch_service.transports.BatchServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BatchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_job", + "get_job", + "delete_job", + "list_jobs", + "get_task", + "list_tasks", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_batch_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.batch_v1alpha.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BatchServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_batch_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.batch_v1alpha.services.batch_service.transports.BatchServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BatchServiceTransport() + adc.assert_called_once() + + +def test_batch_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + BatchServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BatchServiceGrpcTransport, + transports.BatchServiceGrpcAsyncIOTransport, + ], +) +def test_batch_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BatchServiceGrpcTransport, + transports.BatchServiceGrpcAsyncIOTransport, + transports.BatchServiceRestTransport, + ], +) +def test_batch_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.BatchServiceGrpcTransport, grpc_helpers), + (transports.BatchServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_batch_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "batch.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="batch.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], +) +def test_batch_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_batch_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.BatchServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_batch_service_rest_lro_client(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_batch_service_host_no_port(transport_name): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="batch.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "batch.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_batch_service_host_with_port(transport_name): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="batch.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "batch.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://batch.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_batch_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BatchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BatchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_job._session + session2 = client2.transport.create_job._session + assert session1 != session2 + session1 = client1.transport.get_job._session + session2 = client2.transport.get_job._session + assert session1 != session2 + session1 = client1.transport.delete_job._session + session2 = client2.transport.delete_job._session + assert session1 != session2 + session1 = client1.transport.list_jobs._session + session2 = client2.transport.list_jobs._session + assert session1 != session2 + session1 = client1.transport.get_task._session + session2 = client2.transport.get_task._session + assert session1 != session2 + session1 = client1.transport.list_tasks._session + session2 = client2.transport.list_tasks._session + assert session1 != session2 + + +def test_batch_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BatchServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_batch_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BatchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], +) +def test_batch_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], +) +def test_batch_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_batch_service_grpc_lro_client(): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_batch_service_grpc_lro_async_client(): + client = BatchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_job_path(): + project = "squid" + location = "clam" + job = "whelk" + expected = "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) + actual = BatchServiceClient.job_path(project, location, job) + assert expected == actual + + +def test_parse_job_path(): + expected = { + "project": "octopus", + "location": "oyster", + "job": "nudibranch", + } + path = BatchServiceClient.job_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_job_path(path) + assert expected == actual + + +def test_task_path(): + project = "cuttlefish" + location = "mussel" + job = "winkle" + task_group = "nautilus" + task = "scallop" + expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}/tasks/{task}".format( + project=project, + location=location, + job=job, + task_group=task_group, + task=task, + ) + actual = BatchServiceClient.task_path(project, location, job, task_group, task) + assert expected == actual + + +def test_parse_task_path(): + expected = { + "project": "abalone", + "location": "squid", + "job": "clam", + "task_group": "whelk", + "task": "octopus", + } + path = BatchServiceClient.task_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_task_path(path) + assert expected == actual + + +def test_task_group_path(): + project = "oyster" + location = "nudibranch" + job = "cuttlefish" + task_group = "mussel" + expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}".format( + project=project, + location=location, + job=job, + task_group=task_group, + ) + actual = BatchServiceClient.task_group_path(project, location, job, task_group) + assert expected == actual + + +def test_parse_task_group_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "job": "scallop", + "task_group": "abalone", + } + path = BatchServiceClient.task_group_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_task_group_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = BatchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = BatchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = BatchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = BatchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = BatchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = BatchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = BatchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = BatchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.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, + ) + actual = BatchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = BatchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BatchServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.BatchServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.BatchServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = BatchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_batch_service_host_no_port(transport_name): +@pytest.mark.asyncio +async def test_transport_close_async(): + client = BatchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="batch.googleapis.com" - ), - transport=transport_name, + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) - assert client.transport._host == ("batch.googleapis.com:443") + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + locations_pb2.GetLocationRequest, + dict, ], ) -def test_batch_service_host_with_port(transport_name): +def test_get_location_rest(request_type): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="batch.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("batch.googleapis.com:8000") + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_batch_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that channel is used if provided. - transport = transports.BatchServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + response = client.get_location(request) + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_batch_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.BatchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, +def test_list_locations_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", - [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], ) -def test_batch_service_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +def test_list_locations_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/jobs/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", - [transports.BatchServiceGrpcTransport, transports.BatchServiceGrpcAsyncIOTransport], + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], ) -def test_batch_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() +def test_get_iam_policy_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - 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, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) -def test_batch_service_grpc_lro_client(): + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/jobs/sample3"}, request ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) -def test_batch_service_grpc_lro_async_client(): - client = BatchServiceAsyncClient( +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - transport = client.transport + request_init = {"resource": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) -def test_job_path(): - project = "squid" - location = "clam" - job = "whelk" - expected = "projects/{project}/locations/{location}/jobs/{job}".format( - project=project, - location=location, - job=job, - ) - actual = BatchServiceClient.job_path(project, location, job) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) -def test_parse_job_path(): - expected = { - "project": "octopus", - "location": "oyster", - "job": "nudibranch", - } - path = BatchServiceClient.job_path(**expected) +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/jobs/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_job_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) -def test_task_path(): - project = "cuttlefish" - location = "mussel" - job = "winkle" - task_group = "nautilus" - task = "scallop" - expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}/tasks/{task}".format( - project=project, - location=location, - job=job, - task_group=task_group, - task=task, +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.task_path(project, location, job, task_group, task) - assert expected == actual + request_init = {"resource": "projects/sample1/locations/sample2/jobs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_parse_task_path(): - expected = { - "project": "abalone", - "location": "squid", - "job": "clam", - "task_group": "whelk", - "task": "octopus", - } - path = BatchServiceClient.task_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_task_path(path) - assert expected == actual + response = client.test_iam_permissions(request) + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_task_group_path(): - project = "oyster" - location = "nudibranch" - job = "cuttlefish" - task_group = "mussel" - expected = "projects/{project}/locations/{location}/jobs/{job}/taskGroups/{task_group}".format( - project=project, - location=location, - job=job, - task_group=task_group, - ) - actual = BatchServiceClient.task_group_path(project, location, job, task_group) - assert expected == actual +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_task_group_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "job": "scallop", - "task_group": "abalone", - } - path = BatchServiceClient.task_group_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_task_group_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.common_billing_account_path(billing_account) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = BatchServiceClient.common_billing_account_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_billing_account_path(path) - assert expected == actual + response = client.cancel_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = BatchServiceClient.common_folder_path(folder) - assert expected == actual +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = BatchServiceClient.common_folder_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_folder_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.common_organization_path(organization) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = BatchServiceClient.common_organization_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_organization_path(path) - assert expected == actual + response = client.delete_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) - actual = BatchServiceClient.common_project_path(project) - assert expected == actual +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = BatchServiceClient.common_project_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_project_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = BatchServiceClient.common_location_path(project, location) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = BatchServiceClient.common_location_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = BatchServiceClient.parse_common_location_path(path) - assert expected == actual + response = client.get_operation(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.BatchServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = BatchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = BatchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - with mock.patch.object( - transports.BatchServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = BatchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = BatchServiceAsyncClient( + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = BatchServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) def test_delete_operation(transport: str = "grpc"): @@ -4604,6 +7163,7 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4621,6 +7181,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: