diff --git a/.generator/cli.py b/.generator/cli.py index a9491a400e25..2f2b62cd4882 100644 --- a/.generator/cli.py +++ b/.generator/cli.py @@ -23,6 +23,7 @@ import subprocess import sys import tempfile +import time import yaml from datetime import date, datetime from functools import lru_cache @@ -31,6 +32,40 @@ import build.util import parse_googleapis_content +logging.basicConfig(stream=sys.stdout, level=logging.INFO) + +import functools + +PERF_LOGGING_ENABLED = os.environ.get("ENABLE_PERF_LOGS") == "1" + +if PERF_LOGGING_ENABLED: + perf_logger = logging.getLogger("performance_metrics") + perf_logger.setLevel(logging.INFO) + perf_handler = logging.FileHandler("/tmp/performance_metrics.log", mode='w') + perf_formatter = logging.Formatter('%(asctime)s | %(message)s', datefmt='%H:%M:%S') + perf_handler.setFormatter(perf_formatter) + perf_logger.addHandler(perf_handler) + perf_logger.propagate = False + +def track_time(func): + """ + Decorator. Usage: @track_time + If logging is OFF, it returns the original function (Zero Overhead). + If logging is ON, it wraps the function to measure execution time. + """ + if not PERF_LOGGING_ENABLED: + return func + + @functools.wraps(func) + def wrapper(*args, **kwargs): + start_time = time.perf_counter() + try: + return func(*args, **kwargs) + finally: + duration = time.perf_counter() - start_time + perf_logger.info(f"{func.__name__:<30} | {duration:.4f} seconds") + + return wrapper try: import synthtool @@ -323,8 +358,9 @@ def _get_library_id(request_data: Dict) -> str: return library_id +@track_time def _run_post_processor(output: str, library_id: str, is_mono_repo: bool): - """Runs the synthtool post-processor on the output directory. + """Runs the synthtool post-processor (templates) and Ruff formatter (lint/format). Args: output(str): Path to the directory in the container where code @@ -334,25 +370,58 @@ def _run_post_processor(output: str, library_id: str, is_mono_repo: bool): """ os.chdir(output) path_to_library = f"packages/{library_id}" if is_mono_repo else "." - logger.info("Running Python post-processor...") + + # 1. Run Synthtool (Templates & Fixers only) + # Note: This relies on 'nox' being disabled in your environment (via run_fast.sh shim) + # to avoid the slow formatting step inside owlbot. + logger.info("Running Python post-processor (Templates & Fixers)...") if SYNTHTOOL_INSTALLED: - if is_mono_repo: - python_mono_repo.owlbot_main(path_to_library) - else: - # Some repositories have customizations in `librarian.py`. - # If this file exists, run those customizations instead of `owlbot_main` - if Path(f"{output}/librarian.py").exists(): - subprocess.run(["python3.14", f"{output}/librarian.py"]) + try: + if is_mono_repo: + python_mono_repo.owlbot_main(path_to_library) else: - python.owlbot_main() - else: - raise SYNTHTOOL_IMPORT_ERROR # pragma: NO COVER + # Handle custom librarian scripts if present + if Path(f"{output}/librarian.py").exists(): + subprocess.run(["python3.14", f"{output}/librarian.py"]) + else: + python.owlbot_main() + except Exception as e: + logger.warning(f"Synthtool warning (non-fatal): {e}") + + # 2. Run RUFF (Fast Formatter & Import Sorter) + # This replaces both 'isort' and 'black' and runs in < 1 second. + # We hardcode flags here to match Black defaults so you don't need config files. + # logger.info("🚀 Running Ruff (Fast Formatter)...") + try: + # STEP A: Fix Imports (like isort) + subprocess.run( + [ + "ruff", "check", + "--select", "I", # Only run Import sorting rules + "--fix", # Auto-fix them + "--line-length=88", # Match Black default + "--known-first-party=google", # Prevent 'google' moving to 3rd party block + output + ], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) - # If there is no noxfile, run `isort`` and `black` on the output. - # This is required for proto-only libraries which are not GAPIC. - if not Path(f"{output}/{path_to_library}/noxfile.py").exists(): - subprocess.run(["isort", output]) - subprocess.run(["black", output]) + # STEP B: Format Code (like black) + subprocess.run( + [ + "ruff", "format", + "--line-length=88", # Match Black default + output + ], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) + except FileNotFoundError: + logger.warning("⚠️ Ruff binary not found. Code will be unformatted.") + logger.warning(" Please run: pip install ruff") logger.info("Python post-processor ran successfully.") @@ -392,6 +461,7 @@ def _add_header_to_files(directory: str) -> None: f.writelines(lines) +@track_time def _copy_files_needed_for_post_processing( output: str, input: str, library_id: str, is_mono_repo: bool ): @@ -444,6 +514,7 @@ def _copy_files_needed_for_post_processing( ) +@track_time def _clean_up_files_after_post_processing( output: str, library_id: str, is_mono_repo: bool ): @@ -590,6 +661,7 @@ def _get_repo_name_from_repo_metadata(base: str, library_id: str, is_mono_repo: return repo_name +@track_time def _generate_repo_metadata_file( output: str, library_id: str, source: str, apis: List[Dict], is_mono_repo: bool ): @@ -631,6 +703,7 @@ def _generate_repo_metadata_file( _write_json_file(output_repo_metadata, metadata_content) +@track_time def _copy_readme_to_docs(output: str, library_id: str, is_mono_repo: bool): """Copies the README.rst file for a generated library to docs/README.rst. @@ -672,6 +745,7 @@ def _copy_readme_to_docs(output: str, library_id: str, is_mono_repo: bool): f.write(content) +@track_time def handle_generate( librarian: str = LIBRARIAN_DIR, source: str = SOURCE_DIR, @@ -933,6 +1007,7 @@ def _stage_gapic_library(tmp_dir: str, staging_dir: str) -> None: shutil.copytree(tmp_dir, staging_dir, dirs_exist_ok=True) +@track_time def _generate_api( api_path: str, library_id: str, @@ -1748,6 +1823,7 @@ def handle_release_stage( output=args.output, input=args.input, ) + elif args.command == "build": args.func(librarian=args.librarian, repo=args.repo) elif args.command == "release-stage": diff --git a/.generator/requirements.in b/.generator/requirements.in index 87adc6d50599..a50710f429cc 100644 --- a/.generator/requirements.in +++ b/.generator/requirements.in @@ -3,5 +3,4 @@ gapic-generator==1.30.3 # Fix mypy checks https://github.com/googleapis/gapic-ge nox starlark-pyo3>=2025.1 build -black==23.7.0 -isort==5.11.0 +ruff \ No newline at end of file diff --git a/.librarian/generate-request.json b/.librarian/generate-request.json new file mode 100644 index 000000000000..31b573bd01da --- /dev/null +++ b/.librarian/generate-request.json @@ -0,0 +1,40 @@ +{ + "id": "google-cloud-vision", + "version": "3.12.0", + "apis": [ + { + "path": "google/cloud/vision/v1p3beta1", + "service_config": "vision_v1p3beta1.yaml" + }, + { + "path": "google/cloud/vision/v1", + "service_config": "vision_v1.yaml" + }, + { + "path": "google/cloud/vision/v1p1beta1", + "service_config": "vision_v1p1beta1.yaml" + }, + { + "path": "google/cloud/vision/v1p2beta1", + "service_config": "vision_v1p2beta1.yaml" + }, + { + "path": "google/cloud/vision/v1p4beta1", + "service_config": "vision_v1p4beta1.yaml" + } + ], + "source_roots": [ + "packages/google-cloud-vision" + ], + "preserve_regex": [ + "packages/google-cloud-vision/CHANGELOG.md", + "docs/CHANGELOG.md", + "samples/README.txt", + "samples/snippets/README.rst", + "tests/system" + ], + "remove_regex": [ + "packages/google-cloud-vision/" + ], + "tag_format": "{id}-v{version}" +} \ No newline at end of file diff --git a/packages/google-cloud-vision/docs/conf.py b/packages/google-cloud-vision/docs/conf.py index e8dcac6902ba..0b8a5fcc323a 100644 --- a/packages/google-cloud-vision/docs/conf.py +++ b/packages/google-cloud-vision/docs/conf.py @@ -25,9 +25,9 @@ # All configuration values have a default; values that are commented out # serve to show the default. +import sys import os import shlex -import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -81,9 +81,9 @@ root_doc = "index" # General information about the project. -project = "google-cloud-vision" -copyright = "2025, Google, LLC" -author = "Google APIs" +project = u"google-cloud-vision" +copyright = u"2025, Google, LLC" +author = u"Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -283,7 +283,7 @@ ( root_doc, "google-cloud-vision.tex", - "google-cloud-vision Documentation", + u"google-cloud-vision Documentation", author, "manual", ) diff --git a/packages/google-cloud-vision/google/cloud/vision/__init__.py b/packages/google-cloud-vision/google/cloud/vision/__init__.py index 271a36da1815..407f2fc74ef2 100644 --- a/packages/google-cloud-vision/google/cloud/vision/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision/__init__.py @@ -18,196 +18,182 @@ __version__ = package_version.__version__ -from google.cloud.vision_v1.services.image_annotator.async_client import ( - ImageAnnotatorAsyncClient, -) from google.cloud.vision_v1 import ImageAnnotatorClient -from google.cloud.vision_v1.services.product_search.async_client import ( - ProductSearchAsyncClient, -) +from google.cloud.vision_v1.services.image_annotator.async_client import ImageAnnotatorAsyncClient from google.cloud.vision_v1.services.product_search.client import ProductSearchClient -from google.cloud.vision_v1.types.geometry import ( - BoundingPoly, - NormalizedVertex, - Position, - Vertex, -) -from google.cloud.vision_v1.types.image_annotator import ( - AnnotateFileRequest, - AnnotateFileResponse, - AnnotateImageRequest, - AnnotateImageResponse, - AsyncAnnotateFileRequest, - AsyncAnnotateFileResponse, - AsyncBatchAnnotateFilesRequest, - AsyncBatchAnnotateFilesResponse, - AsyncBatchAnnotateImagesRequest, - AsyncBatchAnnotateImagesResponse, - BatchAnnotateFilesRequest, - BatchAnnotateFilesResponse, - BatchAnnotateImagesRequest, - BatchAnnotateImagesResponse, - ColorInfo, - CropHint, - CropHintsAnnotation, - CropHintsParams, - DominantColorsAnnotation, - EntityAnnotation, - FaceAnnotation, - Feature, - GcsDestination, - GcsSource, - Image, - ImageAnnotationContext, - ImageContext, - ImageProperties, - ImageSource, - InputConfig, - LatLongRect, - Likelihood, - LocalizedObjectAnnotation, - LocationInfo, - OperationMetadata, - OutputConfig, - Property, - SafeSearchAnnotation, - TextDetectionParams, - WebDetectionParams, -) -from google.cloud.vision_v1.types.product_search import ( - ProductSearchParams, - ProductSearchResults, -) -from google.cloud.vision_v1.types.product_search_service import ( - AddProductToProductSetRequest, - BatchOperationMetadata, - CreateProductRequest, - CreateProductSetRequest, - CreateReferenceImageRequest, - DeleteProductRequest, - DeleteProductSetRequest, - DeleteReferenceImageRequest, - GetProductRequest, - GetProductSetRequest, - GetReferenceImageRequest, - ImportProductSetsGcsSource, - ImportProductSetsInputConfig, - ImportProductSetsRequest, - ImportProductSetsResponse, - ListProductSetsRequest, - ListProductSetsResponse, - ListProductsInProductSetRequest, - ListProductsInProductSetResponse, - ListProductsRequest, - ListProductsResponse, - ListReferenceImagesRequest, - ListReferenceImagesResponse, - Product, - ProductSet, - ProductSetPurgeConfig, - PurgeProductsRequest, - ReferenceImage, - RemoveProductFromProductSetRequest, - UpdateProductRequest, - UpdateProductSetRequest, -) -from google.cloud.vision_v1.types.text_annotation import ( - Block, - Page, - Paragraph, - Symbol, - TextAnnotation, - Word, -) +from google.cloud.vision_v1.services.product_search.async_client import ProductSearchAsyncClient + +from google.cloud.vision_v1.types.geometry import BoundingPoly +from google.cloud.vision_v1.types.geometry import NormalizedVertex +from google.cloud.vision_v1.types.geometry import Position +from google.cloud.vision_v1.types.geometry import Vertex +from google.cloud.vision_v1.types.image_annotator import AnnotateFileRequest +from google.cloud.vision_v1.types.image_annotator import AnnotateFileResponse +from google.cloud.vision_v1.types.image_annotator import AnnotateImageRequest +from google.cloud.vision_v1.types.image_annotator import AnnotateImageResponse +from google.cloud.vision_v1.types.image_annotator import AsyncAnnotateFileRequest +from google.cloud.vision_v1.types.image_annotator import AsyncAnnotateFileResponse +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateFilesRequest +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateFilesResponse +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateImagesRequest +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateImagesResponse +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateFilesRequest +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateFilesResponse +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateImagesRequest +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateImagesResponse +from google.cloud.vision_v1.types.image_annotator import ColorInfo +from google.cloud.vision_v1.types.image_annotator import CropHint +from google.cloud.vision_v1.types.image_annotator import CropHintsAnnotation +from google.cloud.vision_v1.types.image_annotator import CropHintsParams +from google.cloud.vision_v1.types.image_annotator import DominantColorsAnnotation +from google.cloud.vision_v1.types.image_annotator import EntityAnnotation +from google.cloud.vision_v1.types.image_annotator import FaceAnnotation +from google.cloud.vision_v1.types.image_annotator import Feature +from google.cloud.vision_v1.types.image_annotator import GcsDestination +from google.cloud.vision_v1.types.image_annotator import GcsSource +from google.cloud.vision_v1.types.image_annotator import Image +from google.cloud.vision_v1.types.image_annotator import ImageAnnotationContext +from google.cloud.vision_v1.types.image_annotator import ImageContext +from google.cloud.vision_v1.types.image_annotator import ImageProperties +from google.cloud.vision_v1.types.image_annotator import ImageSource +from google.cloud.vision_v1.types.image_annotator import InputConfig +from google.cloud.vision_v1.types.image_annotator import LatLongRect +from google.cloud.vision_v1.types.image_annotator import LocalizedObjectAnnotation +from google.cloud.vision_v1.types.image_annotator import LocationInfo +from google.cloud.vision_v1.types.image_annotator import OperationMetadata +from google.cloud.vision_v1.types.image_annotator import OutputConfig +from google.cloud.vision_v1.types.image_annotator import Property +from google.cloud.vision_v1.types.image_annotator import SafeSearchAnnotation +from google.cloud.vision_v1.types.image_annotator import TextDetectionParams +from google.cloud.vision_v1.types.image_annotator import WebDetectionParams +from google.cloud.vision_v1.types.image_annotator import Likelihood +from google.cloud.vision_v1.types.product_search import ProductSearchParams +from google.cloud.vision_v1.types.product_search import ProductSearchResults +from google.cloud.vision_v1.types.product_search_service import AddProductToProductSetRequest +from google.cloud.vision_v1.types.product_search_service import BatchOperationMetadata +from google.cloud.vision_v1.types.product_search_service import CreateProductRequest +from google.cloud.vision_v1.types.product_search_service import CreateProductSetRequest +from google.cloud.vision_v1.types.product_search_service import CreateReferenceImageRequest +from google.cloud.vision_v1.types.product_search_service import DeleteProductRequest +from google.cloud.vision_v1.types.product_search_service import DeleteProductSetRequest +from google.cloud.vision_v1.types.product_search_service import DeleteReferenceImageRequest +from google.cloud.vision_v1.types.product_search_service import GetProductRequest +from google.cloud.vision_v1.types.product_search_service import GetProductSetRequest +from google.cloud.vision_v1.types.product_search_service import GetReferenceImageRequest +from google.cloud.vision_v1.types.product_search_service import ImportProductSetsGcsSource +from google.cloud.vision_v1.types.product_search_service import ImportProductSetsInputConfig +from google.cloud.vision_v1.types.product_search_service import ImportProductSetsRequest +from google.cloud.vision_v1.types.product_search_service import ImportProductSetsResponse +from google.cloud.vision_v1.types.product_search_service import ListProductSetsRequest +from google.cloud.vision_v1.types.product_search_service import ListProductSetsResponse +from google.cloud.vision_v1.types.product_search_service import ListProductsInProductSetRequest +from google.cloud.vision_v1.types.product_search_service import ListProductsInProductSetResponse +from google.cloud.vision_v1.types.product_search_service import ListProductsRequest +from google.cloud.vision_v1.types.product_search_service import ListProductsResponse +from google.cloud.vision_v1.types.product_search_service import ListReferenceImagesRequest +from google.cloud.vision_v1.types.product_search_service import ListReferenceImagesResponse +from google.cloud.vision_v1.types.product_search_service import Product +from google.cloud.vision_v1.types.product_search_service import ProductSet +from google.cloud.vision_v1.types.product_search_service import ProductSetPurgeConfig +from google.cloud.vision_v1.types.product_search_service import PurgeProductsRequest +from google.cloud.vision_v1.types.product_search_service import ReferenceImage +from google.cloud.vision_v1.types.product_search_service import RemoveProductFromProductSetRequest +from google.cloud.vision_v1.types.product_search_service import UpdateProductRequest +from google.cloud.vision_v1.types.product_search_service import UpdateProductSetRequest +from google.cloud.vision_v1.types.text_annotation import Block +from google.cloud.vision_v1.types.text_annotation import Page +from google.cloud.vision_v1.types.text_annotation import Paragraph +from google.cloud.vision_v1.types.text_annotation import Symbol +from google.cloud.vision_v1.types.text_annotation import TextAnnotation +from google.cloud.vision_v1.types.text_annotation import Word from google.cloud.vision_v1.types.web_detection import WebDetection -__all__ = ( - "ImageAnnotatorClient", - "ImageAnnotatorAsyncClient", - "ProductSearchClient", - "ProductSearchAsyncClient", - "BoundingPoly", - "NormalizedVertex", - "Position", - "Vertex", - "AnnotateFileRequest", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "Image", - "ImageAnnotationContext", - "ImageContext", - "ImageProperties", - "ImageSource", - "InputConfig", - "LatLongRect", - "LocalizedObjectAnnotation", - "LocationInfo", - "OperationMetadata", - "OutputConfig", - "Property", - "SafeSearchAnnotation", - "TextDetectionParams", - "WebDetectionParams", - "Likelihood", - "ProductSearchParams", - "ProductSearchResults", - "AddProductToProductSetRequest", - "BatchOperationMetadata", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "Product", - "ProductSet", - "ProductSetPurgeConfig", - "PurgeProductsRequest", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Block", - "Page", - "Paragraph", - "Symbol", - "TextAnnotation", - "Word", - "WebDetection", +__all__ = ('ImageAnnotatorClient', + 'ImageAnnotatorAsyncClient', + 'ProductSearchClient', + 'ProductSearchAsyncClient', + 'BoundingPoly', + 'NormalizedVertex', + 'Position', + 'Vertex', + 'AnnotateFileRequest', + 'AnnotateFileResponse', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'AsyncBatchAnnotateImagesRequest', + 'AsyncBatchAnnotateImagesResponse', + 'BatchAnnotateFilesRequest', + 'BatchAnnotateFilesResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'ColorInfo', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'DominantColorsAnnotation', + 'EntityAnnotation', + 'FaceAnnotation', + 'Feature', + 'GcsDestination', + 'GcsSource', + 'Image', + 'ImageAnnotationContext', + 'ImageContext', + 'ImageProperties', + 'ImageSource', + 'InputConfig', + 'LatLongRect', + 'LocalizedObjectAnnotation', + 'LocationInfo', + 'OperationMetadata', + 'OutputConfig', + 'Property', + 'SafeSearchAnnotation', + 'TextDetectionParams', + 'WebDetectionParams', + 'Likelihood', + 'ProductSearchParams', + 'ProductSearchResults', + 'AddProductToProductSetRequest', + 'BatchOperationMetadata', + 'CreateProductRequest', + 'CreateProductSetRequest', + 'CreateReferenceImageRequest', + 'DeleteProductRequest', + 'DeleteProductSetRequest', + 'DeleteReferenceImageRequest', + 'GetProductRequest', + 'GetProductSetRequest', + 'GetReferenceImageRequest', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ListProductsRequest', + 'ListProductsResponse', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'Product', + 'ProductSet', + 'ProductSetPurgeConfig', + 'PurgeProductsRequest', + 'ReferenceImage', + 'RemoveProductFromProductSetRequest', + 'UpdateProductRequest', + 'UpdateProductSetRequest', + 'Block', + 'Page', + 'Paragraph', + 'Symbol', + 'TextAnnotation', + 'Word', + 'WebDetection', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1/__init__.py index 99375917c1b9..4a138f8763ff 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/__init__.py @@ -13,11 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import sys +from google.cloud.vision_v1 import gapic_version as package_version import google.api_core as api_core - -from google.cloud.vision_v1 import gapic_version as package_version +import sys __version__ = package_version.__version__ @@ -28,125 +27,124 @@ # this code path once we drop support for Python 3.7 import importlib_metadata as metadata -from google.cloud.vision_helpers import VisionHelpers -from google.cloud.vision_helpers.decorators import add_single_feature_methods +from .services.image_annotator import ImageAnnotatorClient from .services.image_annotator import ImageAnnotatorAsyncClient -from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient -from .services.product_search import ProductSearchAsyncClient, ProductSearchClient -from .types.geometry import BoundingPoly, NormalizedVertex, Position, Vertex -from .types.image_annotator import ( - AnnotateFileRequest, - AnnotateFileResponse, - AnnotateImageRequest, - AnnotateImageResponse, - AsyncAnnotateFileRequest, - AsyncAnnotateFileResponse, - AsyncBatchAnnotateFilesRequest, - AsyncBatchAnnotateFilesResponse, - AsyncBatchAnnotateImagesRequest, - AsyncBatchAnnotateImagesResponse, - BatchAnnotateFilesRequest, - BatchAnnotateFilesResponse, - BatchAnnotateImagesRequest, - BatchAnnotateImagesResponse, - ColorInfo, - CropHint, - CropHintsAnnotation, - CropHintsParams, - DominantColorsAnnotation, - EntityAnnotation, - FaceAnnotation, - Feature, - GcsDestination, - GcsSource, - Image, - ImageAnnotationContext, - ImageContext, - ImageProperties, - ImageSource, - InputConfig, - LatLongRect, - Likelihood, - LocalizedObjectAnnotation, - LocationInfo, - OperationMetadata, - OutputConfig, - Property, - SafeSearchAnnotation, - TextDetectionParams, - WebDetectionParams, -) -from .types.product_search import ProductSearchParams, ProductSearchResults -from .types.product_search_service import ( - AddProductToProductSetRequest, - BatchOperationMetadata, - CreateProductRequest, - CreateProductSetRequest, - CreateReferenceImageRequest, - DeleteProductRequest, - DeleteProductSetRequest, - DeleteReferenceImageRequest, - GetProductRequest, - GetProductSetRequest, - GetReferenceImageRequest, - ImportProductSetsGcsSource, - ImportProductSetsInputConfig, - ImportProductSetsRequest, - ImportProductSetsResponse, - ListProductSetsRequest, - ListProductSetsResponse, - ListProductsInProductSetRequest, - ListProductsInProductSetResponse, - ListProductsRequest, - ListProductsResponse, - ListReferenceImagesRequest, - ListReferenceImagesResponse, - Product, - ProductSet, - ProductSetPurgeConfig, - PurgeProductsRequest, - ReferenceImage, - RemoveProductFromProductSetRequest, - UpdateProductRequest, - UpdateProductSetRequest, -) -from .types.text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word +from .services.product_search import ProductSearchClient +from .services.product_search import ProductSearchAsyncClient + +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileRequest +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import AsyncBatchAnnotateImagesRequest +from .types.image_annotator import AsyncBatchAnnotateImagesResponse +from .types.image_annotator import BatchAnnotateFilesRequest +from .types.image_annotator import BatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import LocalizedObjectAnnotation +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import TextDetectionParams +from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood +from .types.product_search import ProductSearchParams +from .types.product_search import ProductSearchResults +from .types.product_search_service import AddProductToProductSetRequest +from .types.product_search_service import BatchOperationMetadata +from .types.product_search_service import CreateProductRequest +from .types.product_search_service import CreateProductSetRequest +from .types.product_search_service import CreateReferenceImageRequest +from .types.product_search_service import DeleteProductRequest +from .types.product_search_service import DeleteProductSetRequest +from .types.product_search_service import DeleteReferenceImageRequest +from .types.product_search_service import GetProductRequest +from .types.product_search_service import GetProductSetRequest +from .types.product_search_service import GetReferenceImageRequest +from .types.product_search_service import ImportProductSetsGcsSource +from .types.product_search_service import ImportProductSetsInputConfig +from .types.product_search_service import ImportProductSetsRequest +from .types.product_search_service import ImportProductSetsResponse +from .types.product_search_service import ListProductSetsRequest +from .types.product_search_service import ListProductSetsResponse +from .types.product_search_service import ListProductsInProductSetRequest +from .types.product_search_service import ListProductsInProductSetResponse +from .types.product_search_service import ListProductsRequest +from .types.product_search_service import ListProductsResponse +from .types.product_search_service import ListReferenceImagesRequest +from .types.product_search_service import ListReferenceImagesResponse +from .types.product_search_service import Product +from .types.product_search_service import ProductSet +from .types.product_search_service import ProductSetPurgeConfig +from .types.product_search_service import PurgeProductsRequest +from .types.product_search_service import ReferenceImage +from .types.product_search_service import RemoveProductFromProductSetRequest +from .types.product_search_service import UpdateProductRequest +from .types.product_search_service import UpdateProductSetRequest +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word from .types.web_detection import WebDetection -if hasattr(api_core, "check_python_version") and hasattr( - api_core, "check_dependency_versions" -): # pragma: NO COVER - api_core.check_python_version("google.cloud.vision_v1") # type: ignore - api_core.check_dependency_versions("google.cloud.vision_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.cloud.vision_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.vision_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: - import sys import warnings + import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.vision_v1" if sys.version_info < (3, 9): - warnings.warn( - "You are using a non-supported Python version " - + f"({_py_version_str}). Google will not post any further " - + f"updates to {_package_label} supporting this Python version. " - + "Please upgrade to the latest Python version, or at " - + f"least to Python 3.9, and then update {_package_label}.", - FutureWarning, - ) + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning) if sys.version_info[:2] == (3, 9): - warnings.warn( - f"You are using a Python version ({_py_version_str}) " - + f"which Google will stop supporting in {_package_label} in " - + "January 2026. Please " - + "upgrade to the latest Python version, or at " - + "least to Python 3.10, before then, and " - + f"then update {_package_label}.", - FutureWarning, - ) + warnings.warn(f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -184,124 +182,113 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn( - f"Package {_package_label} depends on " - + f"{_dependency_package}, currently installed at version " - + f"{_version_used_string}. Future updates to " - + f"{_package_label} will require {_dependency_package} at " - + f"version {_next_supported_version} or higher{_recommendation}." - + " Please ensure " - + "that either (a) your Python environment doesn't pin the " - + f"version of {_dependency_package}, so that updates to " - + f"{_package_label} can require the higher version, or " - + "(b) you manually update your Python environment to use at " - + f"least version {_next_supported_version} of " - + f"{_dependency_package}.", - FutureWarning, - ) + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) except Exception: - warnings.warn( - "Could not determine the version of Python " - + "currently being used. To continue receiving " - + "updates for {_package_label}, ensure you are " - + "using a supported version of Python; see " - + "https://devguide.python.org/versions/" - ) - - -@add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): - __doc__ = IacImageAnnotatorClient.__doc__ - Feature = Feature - + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") __all__ = ( - "ImageAnnotatorAsyncClient", - "ProductSearchAsyncClient", - "AddProductToProductSetRequest", - "AnnotateFileRequest", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "BatchOperationMetadata", - "Block", - "BoundingPoly", - "ColorInfo", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "Image", - "ImageAnnotationContext", - "ImageAnnotatorClient", - "ImageContext", - "ImageProperties", - "ImageSource", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "InputConfig", - "LatLongRect", - "Likelihood", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "LocalizedObjectAnnotation", - "LocationInfo", - "NormalizedVertex", - "OperationMetadata", - "OutputConfig", - "Page", - "Paragraph", - "Position", - "Product", - "ProductSearchClient", - "ProductSearchParams", - "ProductSearchResults", - "ProductSet", - "ProductSetPurgeConfig", - "Property", - "PurgeProductsRequest", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "SafeSearchAnnotation", - "Symbol", - "TextAnnotation", - "TextDetectionParams", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Vertex", - "WebDetection", - "WebDetectionParams", - "Word", + 'ImageAnnotatorAsyncClient', + 'ProductSearchAsyncClient', +'AddProductToProductSetRequest', +'AnnotateFileRequest', +'AnnotateFileResponse', +'AnnotateImageRequest', +'AnnotateImageResponse', +'AsyncAnnotateFileRequest', +'AsyncAnnotateFileResponse', +'AsyncBatchAnnotateFilesRequest', +'AsyncBatchAnnotateFilesResponse', +'AsyncBatchAnnotateImagesRequest', +'AsyncBatchAnnotateImagesResponse', +'BatchAnnotateFilesRequest', +'BatchAnnotateFilesResponse', +'BatchAnnotateImagesRequest', +'BatchAnnotateImagesResponse', +'BatchOperationMetadata', +'Block', +'BoundingPoly', +'ColorInfo', +'CreateProductRequest', +'CreateProductSetRequest', +'CreateReferenceImageRequest', +'CropHint', +'CropHintsAnnotation', +'CropHintsParams', +'DeleteProductRequest', +'DeleteProductSetRequest', +'DeleteReferenceImageRequest', +'DominantColorsAnnotation', +'EntityAnnotation', +'FaceAnnotation', +'Feature', +'GcsDestination', +'GcsSource', +'GetProductRequest', +'GetProductSetRequest', +'GetReferenceImageRequest', +'Image', +'ImageAnnotationContext', +'ImageAnnotatorClient', +'ImageContext', +'ImageProperties', +'ImageSource', +'ImportProductSetsGcsSource', +'ImportProductSetsInputConfig', +'ImportProductSetsRequest', +'ImportProductSetsResponse', +'InputConfig', +'LatLongRect', +'Likelihood', +'ListProductSetsRequest', +'ListProductSetsResponse', +'ListProductsInProductSetRequest', +'ListProductsInProductSetResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListReferenceImagesRequest', +'ListReferenceImagesResponse', +'LocalizedObjectAnnotation', +'LocationInfo', +'NormalizedVertex', +'OperationMetadata', +'OutputConfig', +'Page', +'Paragraph', +'Position', +'Product', +'ProductSearchClient', +'ProductSearchParams', +'ProductSearchResults', +'ProductSet', +'ProductSetPurgeConfig', +'Property', +'PurgeProductsRequest', +'ReferenceImage', +'RemoveProductFromProductSetRequest', +'SafeSearchAnnotation', +'Symbol', +'TextAnnotation', +'TextDetectionParams', +'UpdateProductRequest', +'UpdateProductSetRequest', +'Vertex', +'WebDetection', +'WebDetectionParams', +'Word', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/__init__.py index c7f40549e472..b1663fdd632d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ImageAnnotatorAsyncClient from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient __all__ = ( - "ImageAnnotatorClient", - "ImageAnnotatorAsyncClient", + 'ImageAnnotatorClient', + 'ImageAnnotatorAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/async_client.py index 6efcecc5173a..6839ffee6c08 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from google.cloud.vision_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -46,24 +36,20 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.vision_v1.types import image_annotator - -from .client import ImageAnnotatorClient -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ImageAnnotatorAsyncClient: """Service that performs Google Cloud Vision API detection tasks over client images, such as face, landmark, logo, label, and @@ -84,30 +70,16 @@ class ImageAnnotatorAsyncClient: parse_product_path = staticmethod(ImageAnnotatorClient.parse_product_path) product_set_path = staticmethod(ImageAnnotatorClient.product_set_path) parse_product_set_path = staticmethod(ImageAnnotatorClient.parse_product_set_path) - common_billing_account_path = staticmethod( - ImageAnnotatorClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ImageAnnotatorClient.parse_common_billing_account_path - ) + common_billing_account_path = staticmethod(ImageAnnotatorClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageAnnotatorClient.parse_common_billing_account_path) common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) - parse_common_folder_path = staticmethod( - ImageAnnotatorClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ImageAnnotatorClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ImageAnnotatorClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ImageAnnotatorClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageAnnotatorClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageAnnotatorClient.parse_common_organization_path) common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) - parse_common_project_path = staticmethod( - ImageAnnotatorClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ImageAnnotatorClient.parse_common_project_path) common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) - parse_common_location_path = staticmethod( - ImageAnnotatorClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ImageAnnotatorClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -143,9 +115,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -208,16 +178,12 @@ def universe_domain(self) -> str: get_transport_class = ImageAnnotatorClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator async client. Args: @@ -272,43 +238,31 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1.ImageAnnotatorAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "credentialsType": None, - }, + } ) - async def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + async def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -366,14 +320,10 @@ async def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -387,9 +337,7 @@ async def sample_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -405,17 +353,14 @@ async def sample_batch_annotate_images(): # Done; return the response. return response - async def batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateFilesResponse: + async def batch_annotate_files(self, + request: Optional[Union[image_annotator.BatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation for a batch of files. Now only "application/pdf", "image/tiff" and "image/gif" are supported. @@ -480,14 +425,10 @@ async def sample_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -501,9 +442,7 @@ async def sample_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_files - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_files] # Validate the universe domain. self._client._validate_universe_domain() @@ -519,20 +458,15 @@ async def sample_batch_annotate_files(): # Done; return the response. return response - async def async_batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - output_config: Optional[image_annotator.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def async_batch_annotate_images(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + output_config: Optional[image_annotator.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of images. @@ -614,14 +548,10 @@ async def sample_async_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests, output_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -637,9 +567,7 @@ async def sample_async_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.async_batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.async_batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -663,19 +591,14 @@ async def sample_async_batch_annotate_images(): # Done; return the response. return response - async def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be @@ -746,14 +669,10 @@ async def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -767,9 +686,7 @@ async def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.async_batch_annotate_files - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.async_batch_annotate_files] # Validate the universe domain. self._client._validate_universe_domain() @@ -831,7 +748,8 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), ) # Validate the universe domain. @@ -839,11 +757,7 @@ async def get_operation( # Send the request. response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -854,13 +768,12 @@ async def __aenter__(self) -> "ImageAnnotatorAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorAsyncClient",) +__all__ = ( + "ImageAnnotatorAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/client.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/client.py index 76fbff8ab683..9cfbf978db64 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -63,11 +50,9 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.vision_v1.types import image_annotator - -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -80,18 +65,14 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] _transport_registry["grpc"] = ImageAnnotatorGrpcTransport _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport _transport_registry["rest"] = ImageAnnotatorRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ImageAnnotatorTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. Args: @@ -167,16 +148,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -215,7 +194,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -232,132 +212,84 @@ def transport(self) -> ImageAnnotatorTransport: return self._transport @staticmethod - def product_path( - project: str, - location: str, - product: str, - ) -> str: + def product_path(project: str,location: str,product: str,) -> str: """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + return "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) @staticmethod - def parse_product_path(path: str) -> Dict[str, str]: + def parse_product_path(path: str) -> Dict[str,str]: """Parses a product path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def product_set_path( - project: str, - location: str, - product_set: str, - ) -> str: + def product_set_path(project: str,location: str,product_set: str,) -> str: """Returns a fully-qualified product_set string.""" - return ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + return "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) @staticmethod - def parse_product_set_path(path: str) -> Dict[str, str]: + def parse_product_set_path(path: str) -> Dict[str,str]: """Parses a product_set path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -389,18 +321,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ImageAnnotatorClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -413,9 +341,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -440,9 +366,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -465,9 +389,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -483,25 +405,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -537,18 +451,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -581,16 +492,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator client. Args: @@ -645,24 +552,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ImageAnnotatorClient._read_environment_variables() - self._client_cert_source = ImageAnnotatorClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ImageAnnotatorClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageAnnotatorClient._read_environment_variables() + self._client_cert_source = ImageAnnotatorClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageAnnotatorClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -673,9 +570,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -684,10 +579,8 @@ def __init__( if transport_provided: # transport is a ImageAnnotatorTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -696,29 +589,20 @@ def __init__( self._transport = cast(ImageAnnotatorTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ImageAnnotatorClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ImageAnnotatorClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport] - ] = ( + transport_init: Union[Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport]] = ( ImageAnnotatorClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ImageAnnotatorTransport], transport) @@ -737,41 +621,28 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1.ImageAnnotatorClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "credentialsType": None, - }, + } ) - def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -829,14 +700,10 @@ def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -865,17 +732,14 @@ def sample_batch_annotate_images(): # Done; return the response. return response - def batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateFilesResponse: + def batch_annotate_files(self, + request: Optional[Union[image_annotator.BatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation for a batch of files. Now only "application/pdf", "image/tiff" and "image/gif" are supported. @@ -940,14 +804,10 @@ def sample_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -976,20 +836,15 @@ def sample_batch_annotate_files(): # Done; return the response. return response - def async_batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - output_config: Optional[image_annotator.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def async_batch_annotate_images(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + output_config: Optional[image_annotator.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of images. @@ -1071,14 +926,10 @@ def sample_async_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests, output_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1093,9 +944,7 @@ def sample_async_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.async_batch_annotate_images - ] + rpc = self._transport._wrapped_methods[self._transport.async_batch_annotate_images] # Validate the universe domain. self._validate_universe_domain() @@ -1119,19 +968,14 @@ def sample_async_batch_annotate_images(): # Done; return the response. return response - def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be @@ -1202,14 +1046,10 @@ def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1222,9 +1062,7 @@ def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.async_batch_annotate_files - ] + rpc = self._transport._wrapped_methods[self._transport.async_batch_annotate_files] # Validate the universe domain. self._validate_universe_domain() @@ -1299,7 +1137,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), ) # Validate the universe domain. @@ -1308,11 +1147,7 @@ def get_operation( try: # Send the request. response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1321,11 +1156,18 @@ def get_operation( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorClient",) +__all__ = ( + "ImageAnnotatorClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/__init__.py index 1de28b3fb87a..d3a583db5759 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] -_transport_registry["grpc"] = ImageAnnotatorGrpcTransport -_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport -_transport_registry["rest"] = ImageAnnotatorRestTransport +_transport_registry['grpc'] = ImageAnnotatorGrpcTransport +_transport_registry['grpc_asyncio'] = ImageAnnotatorGrpcAsyncIOTransport +_transport_registry['rest'] = ImageAnnotatorRestTransport __all__ = ( - "ImageAnnotatorTransport", - "ImageAnnotatorGrpcTransport", - "ImageAnnotatorGrpcAsyncIOTransport", - "ImageAnnotatorRestTransport", - "ImageAnnotatorRestInterceptor", + 'ImageAnnotatorTransport', + 'ImageAnnotatorGrpcTransport', + 'ImageAnnotatorGrpcAsyncIOTransport', + 'ImageAnnotatorRestTransport', + 'ImageAnnotatorRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/base.py index 6444874ad13b..dbe3c7a8d54b 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/base.py @@ -16,22 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1 import gapic_version as package_version from google.cloud.vision_v1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,25 +41,24 @@ class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -86,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -96,38 +93,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -202,14 +192,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -219,45 +209,39 @@ def operations_client(self): raise NotImplementedError() @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Union[ - image_annotator.BatchAnnotateImagesResponse, - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Union[ + image_annotator.BatchAnnotateImagesResponse, + Awaitable[image_annotator.BatchAnnotateImagesResponse] + ]]: raise NotImplementedError() @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - Union[ - image_annotator.BatchAnnotateFilesResponse, - Awaitable[image_annotator.BatchAnnotateFilesResponse], - ], - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + Union[ + image_annotator.BatchAnnotateFilesResponse, + Awaitable[image_annotator.BatchAnnotateFilesResponse] + ]]: raise NotImplementedError() @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -274,4 +258,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ImageAnnotatorTransport",) +__all__ = ( + 'ImageAnnotatorTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc.py index a4f87b772d49..60515ff900de 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc.py @@ -16,26 +16,27 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -45,9 +46,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -68,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -79,11 +78,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -98,7 +93,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": client_call_details.method, "response": grpc_response, @@ -123,26 +118,23 @@ class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -266,23 +258,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -318,12 +306,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -343,12 +332,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -364,21 +350,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - image_annotator.BatchAnnotateFilesResponse, - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + image_annotator.BatchAnnotateFilesResponse]: r"""Return a callable for the batch annotate files method over gRPC. Service that performs image detection and annotation @@ -401,20 +384,18 @@ def batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_files" not in self._stubs: - self._stubs["batch_annotate_files"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateFiles", + if 'batch_annotate_files' not in self._stubs: + self._stubs['batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateFiles', request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, ) - return self._stubs["batch_annotate_files"] + return self._stubs['batch_annotate_files'] @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + operations_pb2.Operation]: r"""Return a callable for the async batch annotate images method over gRPC. Run asynchronous image detection and annotation for a list of @@ -440,22 +421,18 @@ def async_batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_images" not in self._stubs: - self._stubs[ - "async_batch_annotate_images" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateImages", + if 'async_batch_annotate_images' not in self._stubs: + self._stubs['async_batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateImages', request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_images"] + return self._stubs['async_batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + operations_pb2.Operation]: r"""Return a callable for the async batch annotate files method over gRPC. Run asynchronous image detection and annotation for a list of @@ -476,15 +453,13 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def close(self): self._logged_channel.close() @@ -493,7 +468,8 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -511,4 +487,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ImageAnnotatorGrpcTransport",) +__all__ = ( + 'ImageAnnotatorGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py index 1c8c7a631000..945f107b65f7 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py @@ -15,31 +15,32 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -47,13 +48,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -74,7 +71,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -85,11 +82,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -104,7 +97,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -134,15 +127,13 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -173,26 +164,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -318,9 +307,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -351,12 +338,9 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse]]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -372,21 +356,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - Awaitable[image_annotator.BatchAnnotateFilesResponse], - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + Awaitable[image_annotator.BatchAnnotateFilesResponse]]: r"""Return a callable for the batch annotate files method over gRPC. Service that performs image detection and annotation @@ -409,21 +390,18 @@ def batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_files" not in self._stubs: - self._stubs["batch_annotate_files"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateFiles", + if 'batch_annotate_files' not in self._stubs: + self._stubs['batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateFiles', request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, ) - return self._stubs["batch_annotate_files"] + return self._stubs['batch_annotate_files'] @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], - Awaitable[operations_pb2.Operation], - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the async batch annotate images method over gRPC. Run asynchronous image detection and annotation for a list of @@ -449,23 +427,18 @@ def async_batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_images" not in self._stubs: - self._stubs[ - "async_batch_annotate_images" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateImages", + if 'async_batch_annotate_images' not in self._stubs: + self._stubs['async_batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateImages', request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_images"] + return self._stubs['async_batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations_pb2.Operation], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the async batch annotate files method over gRPC. Run asynchronous image detection and annotation for a list of @@ -486,18 +459,16 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.batch_annotate_images: self._wrap_method( self.batch_annotate_images, @@ -582,7 +553,8 @@ def kind(self) -> str: def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -596,4 +568,6 @@ def get_operation( return self._stubs["get_operation"] -__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) +__all__ = ( + 'ImageAnnotatorGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest.py index 7c06785750c8..a4c5ebba1ceb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest.py @@ -13,26 +13,33 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -41,7 +48,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -110,15 +116,7 @@ def post_batch_annotate_images(self, response): """ - - def pre_async_batch_annotate_files( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.AsyncBatchAnnotateFilesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnnotateFilesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.AsyncBatchAnnotateFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for async_batch_annotate_files Override in a subclass to manipulate the request or metadata @@ -126,9 +124,7 @@ def pre_async_batch_annotate_files( """ return request, metadata - def post_async_batch_annotate_files( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for async_batch_annotate_files DEPRECATED. Please use the `post_async_batch_annotate_files_with_metadata` @@ -141,11 +137,7 @@ def post_async_batch_annotate_files( """ return response - def post_async_batch_annotate_files_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for async_batch_annotate_files Override in a subclass to read or manipulate the response or metadata after it @@ -160,14 +152,7 @@ def post_async_batch_annotate_files_with_metadata( """ return response, metadata - def pre_async_batch_annotate_images( - self, - request: image_annotator.AsyncBatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.AsyncBatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_async_batch_annotate_images(self, request: image_annotator.AsyncBatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.AsyncBatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for async_batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -175,9 +160,7 @@ def pre_async_batch_annotate_images( """ return request, metadata - def post_async_batch_annotate_images( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_async_batch_annotate_images(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for async_batch_annotate_images DEPRECATED. Please use the `post_async_batch_annotate_images_with_metadata` @@ -190,11 +173,7 @@ def post_async_batch_annotate_images( """ return response - def post_async_batch_annotate_images_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_async_batch_annotate_images_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for async_batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -209,14 +188,7 @@ def post_async_batch_annotate_images_with_metadata( """ return response, metadata - def pre_batch_annotate_files( - self, - request: image_annotator.BatchAnnotateFilesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateFilesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_files(self, request: image_annotator.BatchAnnotateFilesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_files Override in a subclass to manipulate the request or metadata @@ -224,9 +196,7 @@ def pre_batch_annotate_files( """ return request, metadata - def post_batch_annotate_files( - self, response: image_annotator.BatchAnnotateFilesResponse - ) -> image_annotator.BatchAnnotateFilesResponse: + def post_batch_annotate_files(self, response: image_annotator.BatchAnnotateFilesResponse) -> image_annotator.BatchAnnotateFilesResponse: """Post-rpc interceptor for batch_annotate_files DEPRECATED. Please use the `post_batch_annotate_files_with_metadata` @@ -239,14 +209,7 @@ def post_batch_annotate_files( """ return response - def post_batch_annotate_files_with_metadata( - self, - response: image_annotator.BatchAnnotateFilesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateFilesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_files_with_metadata(self, response: image_annotator.BatchAnnotateFilesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateFilesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_files Override in a subclass to read or manipulate the response or metadata after it @@ -261,14 +224,7 @@ def post_batch_annotate_files_with_metadata( """ return response, metadata - def pre_batch_annotate_images( - self, - request: image_annotator.BatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -276,9 +232,7 @@ def pre_batch_annotate_images( """ return request, metadata - def post_batch_annotate_images( - self, response: image_annotator.BatchAnnotateImagesResponse - ) -> image_annotator.BatchAnnotateImagesResponse: + def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImagesResponse) -> image_annotator.BatchAnnotateImagesResponse: """Post-rpc interceptor for batch_annotate_images DEPRECATED. Please use the `post_batch_annotate_images_with_metadata` @@ -291,14 +245,7 @@ def post_batch_annotate_images( """ return response - def post_batch_annotate_images_with_metadata( - self, - response: image_annotator.BatchAnnotateImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_images_with_metadata(self, response: image_annotator.BatchAnnotateImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -314,12 +261,8 @@ def post_batch_annotate_images_with_metadata( return response, metadata def pre_get_operation( - self, - request: operations_pb2.GetOperationRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -361,21 +304,20 @@ class ImageAnnotatorRestTransport(_BaseImageAnnotatorRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ImageAnnotatorRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ImageAnnotatorRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -419,11 +361,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -440,46 +381,40 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # 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.GetOperation": [ + 'google.longrunning.Operations.GetOperation': [ { - "method": "get", - "uri": "/v1/{name=projects/*/operations/*}", + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', }, { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', }, { - "method": "get", - "uri": "/v1/{name=operations/*}", + 'method': 'get', + 'uri': '/v1/{name=operations/*}', }, { - "method": "get", - "uri": "/v1/{name=locations/*/operations/*}", + 'method': 'get', + 'uri': '/v1/{name=locations/*/operations/*}', }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AsyncBatchAnnotateFiles( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, - ImageAnnotatorRestStub, - ): + class _AsyncBatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateFiles") @@ -491,93 +426,77 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: image_annotator.AsyncBatchAnnotateFilesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the async batch annotate - files method over HTTP. - - Args: - request (~.image_annotator.AsyncBatchAnnotateFilesRequest): - The request object. Multiple async file annotation - requests are batched into a single - service call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + files method over HTTP. + + Args: + request (~.image_annotator.AsyncBatchAnnotateFilesRequest): + The request object. Multiple async file annotation + requests are batched into a single + service call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - request, metadata = self._interceptor.pre_async_batch_annotate_files( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_async_batch_annotate_files(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ImageAnnotatorClient.AsyncBatchAnnotateFiles", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "httpRequest": http_request, @@ -586,17 +505,7 @@ def __call__( ) # Send the request - response = ( - ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -609,24 +518,20 @@ def __call__( resp = self._interceptor.post_async_batch_annotate_files(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ImageAnnotatorClient.async_batch_annotate_files", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "metadata": http_response["headers"], @@ -635,10 +540,7 @@ def __call__( ) return resp - class _AsyncBatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _AsyncBatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateImages") @@ -650,92 +552,76 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.AsyncBatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: image_annotator.AsyncBatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the async batch annotate - images method over HTTP. - - Args: - request (~.image_annotator.AsyncBatchAnnotateImagesRequest): - The request object. Request for async image annotation - for a list of images. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + images method over HTTP. + + Args: + request (~.image_annotator.AsyncBatchAnnotateImagesRequest): + The request object. Request for async image annotation + for a list of images. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_async_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_async_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ImageAnnotatorClient.AsyncBatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateImages", "httpRequest": http_request, @@ -744,17 +630,7 @@ def __call__( ) # Send the request - response = ( - ImageAnnotatorRestTransport._AsyncBatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ImageAnnotatorRestTransport._AsyncBatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -767,24 +643,20 @@ def __call__( resp = self._interceptor.post_async_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_async_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_async_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ImageAnnotatorClient.async_batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateImages", "metadata": http_response["headers"], @@ -793,9 +665,7 @@ def __call__( ) return resp - class _BatchAnnotateFiles( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub - ): + class _BatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateFiles") @@ -807,29 +677,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateFilesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateFilesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateFilesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateFilesResponse: r"""Call the batch annotate files method over HTTP. Args: @@ -849,46 +717,32 @@ def __call__( A list of file annotation responses. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_files( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_files(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ImageAnnotatorClient.BatchAnnotateFiles", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "BatchAnnotateFiles", "httpRequest": http_request, @@ -897,15 +751,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateFiles._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateFiles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -920,26 +766,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_files(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_files_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_files_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateFilesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateFilesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ImageAnnotatorClient.batch_annotate_files", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "BatchAnnotateFiles", "metadata": http_response["headers"], @@ -948,10 +788,7 @@ def __call__( ) return resp - class _BatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -963,29 +800,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Call the batch annotate images method over HTTP. Args: @@ -1007,46 +842,32 @@ def __call__( """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ImageAnnotatorClient.BatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "httpRequest": http_request, @@ -1055,15 +876,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1078,26 +891,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateImagesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ImageAnnotatorClient.batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "metadata": http_response["headers"], @@ -1107,54 +914,42 @@ def __call__( return resp @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + 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._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore + return self._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + 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._AsyncBatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._AsyncBatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - image_annotator.BatchAnnotateFilesResponse, - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + image_annotator.BatchAnnotateFilesResponse]: # 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._BatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: # 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._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation( - _BaseImageAnnotatorRestTransport._BaseGetOperation, ImageAnnotatorRestStub - ): + class _GetOperation(_BaseImageAnnotatorRestTransport._BaseGetOperation, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.GetOperation") @@ -1166,28 +961,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: operations_pb2.GetOperationRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. Args: @@ -1205,40 +999,30 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseGetOperation._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseGetOperation._get_http_options() request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseGetOperation._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseGetOperation._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ImageAnnotatorClient.GetOperation", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "GetOperation", "httpRequest": http_request, @@ -1247,14 +1031,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._GetOperation._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ImageAnnotatorRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1265,21 +1042,19 @@ def __call__( resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ImageAnnotatorAsyncClient.GetOperation", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ImageAnnotator", "rpcName": "GetOperation", "httpResponse": http_response, @@ -1296,4 +1071,6 @@ def close(self): self._session.close() -__all__ = ("ImageAnnotatorRestTransport",) +__all__=( + 'ImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest_base.py index 8bbd11f6eb0e..c1211696662f 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest_base.py @@ -14,16 +14,18 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -39,16 +41,14 @@ class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -72,9 +72,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -85,41 +83,37 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAsyncBatchAnnotateFiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/files:asyncBatchAnnotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/files:asyncBatchAnnotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*}/files:asyncBatchAnnotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/files:asyncBatchAnnotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/files:asyncBatchAnnotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/files:asyncBatchAnnotate', + 'body': '*', + }, ] return http_options @@ -134,23 +128,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -159,34 +147,30 @@ class _BaseAsyncBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/images:asyncBatchAnnotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/images:asyncBatchAnnotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*}/images:asyncBatchAnnotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/images:asyncBatchAnnotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/images:asyncBatchAnnotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/images:asyncBatchAnnotate', + 'body': '*', + }, ] return http_options @@ -201,23 +185,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -226,34 +204,30 @@ class _BaseBatchAnnotateFiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/files:annotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/files:annotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*}/files:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/files:annotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/files:annotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/files:annotate', + 'body': '*', + }, ] return http_options @@ -268,23 +242,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -293,34 +261,30 @@ class _BaseBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/images:annotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/images:annotate", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{parent=projects/*}/images:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/images:annotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/images:annotate', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/images:annotate', + 'body': '*', + }, ] return http_options @@ -335,23 +299,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -362,36 +320,38 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=locations/*/operations/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=locations/*/operations/*}', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = json.loads(json.dumps(transcoded_request['query_params'])) return query_params -__all__ = ("_BaseImageAnnotatorRestTransport",) +__all__=( + '_BaseImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/__init__.py index f2e4fe58e8df..ff3cc167408d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ProductSearchAsyncClient from .client import ProductSearchClient +from .async_client import ProductSearchAsyncClient __all__ = ( - "ProductSearchClient", - "ProductSearchAsyncClient", + 'ProductSearchClient', + 'ProductSearchAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/async_client.py index bf2a1db0a73a..8396ac1b3798 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from google.cloud.vision_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -46,47 +36,45 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1.services.product_search import pagers +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore - -from google.cloud.vision_v1.services.product_search import pagers -from google.cloud.vision_v1.types import geometry, product_search_service - -from .client import ProductSearchClient -from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport +from .client import ProductSearchClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ProductSearchAsyncClient: """Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to - put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` """ _client: ProductSearchClient @@ -103,33 +91,17 @@ class ProductSearchAsyncClient: product_set_path = staticmethod(ProductSearchClient.product_set_path) parse_product_set_path = staticmethod(ProductSearchClient.parse_product_set_path) reference_image_path = staticmethod(ProductSearchClient.reference_image_path) - parse_reference_image_path = staticmethod( - ProductSearchClient.parse_reference_image_path - ) - common_billing_account_path = staticmethod( - ProductSearchClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ProductSearchClient.parse_common_billing_account_path - ) + parse_reference_image_path = staticmethod(ProductSearchClient.parse_reference_image_path) + common_billing_account_path = staticmethod(ProductSearchClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductSearchClient.parse_common_billing_account_path) common_folder_path = staticmethod(ProductSearchClient.common_folder_path) - parse_common_folder_path = staticmethod( - ProductSearchClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ProductSearchClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ProductSearchClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ProductSearchClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductSearchClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductSearchClient.parse_common_organization_path) common_project_path = staticmethod(ProductSearchClient.common_project_path) - parse_common_project_path = staticmethod( - ProductSearchClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ProductSearchClient.parse_common_project_path) common_location_path = staticmethod(ProductSearchClient.common_location_path) - parse_common_location_path = staticmethod( - ProductSearchClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ProductSearchClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -165,9 +137,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -230,16 +200,12 @@ def universe_domain(self) -> str: get_transport_class = ProductSearchClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the product search async client. Args: @@ -294,49 +260,39 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1.ProductSearchAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1.ProductSearch", "credentialsType": None, - }, + } ) - async def create_product_set( - self, - request: Optional[ - Union[product_search_service.CreateProductSetRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product_set: Optional[product_search_service.ProductSet] = None, - product_set_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def create_product_set(self, + request: Optional[Union[product_search_service.CreateProductSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. .. code-block:: python @@ -412,14 +368,10 @@ async def sample_create_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product_set, product_set_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -437,14 +389,14 @@ async def sample_create_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -461,23 +413,20 @@ async def sample_create_product_set(): # Done; return the response. return response - async def list_product_sets( - self, - request: Optional[ - Union[product_search_service.ListProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductSetsAsyncPager: + async def list_product_sets(self, + request: Optional[Union[product_search_service.ListProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductSetsAsyncPager: r"""Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. .. code-block:: python @@ -538,14 +487,10 @@ async def sample_list_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -559,14 +504,14 @@ async def sample_list_product_sets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_product_sets - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_product_sets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -594,22 +539,19 @@ async def sample_list_product_sets(): # Done; return the response. return response - async def get_product_set( - self, - request: Optional[ - Union[product_search_service.GetProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def get_product_set(self, + request: Optional[Union[product_search_service.GetProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -670,14 +612,10 @@ async def sample_get_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -691,14 +629,14 @@ async def sample_get_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -715,27 +653,24 @@ async def sample_get_product_set(): # Done; return the response. return response - async def update_product_set( - self, - request: Optional[ - Union[product_search_service.UpdateProductSetRequest, dict] - ] = None, - *, - product_set: Optional[product_search_service.ProductSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def update_product_set(self, + request: Optional[Union[product_search_service.UpdateProductSetRequest, dict]] = None, + *, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. .. code-block:: python @@ -802,14 +737,10 @@ async def sample_update_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product_set, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -825,16 +756,14 @@ async def sample_update_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.update_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product_set.name", request.product_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product_set.name", request.product_set.name), + )), ) # Validate the universe domain. @@ -851,17 +780,14 @@ async def sample_update_product_set(): # Done; return the response. return response - async def delete_product_set( - self, - request: Optional[ - Union[product_search_service.DeleteProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_product_set(self, + request: Optional[Union[product_search_service.DeleteProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a ProductSet. Products and ReferenceImages in the ProductSet are not deleted. @@ -915,14 +841,10 @@ async def sample_delete_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -936,14 +858,14 @@ async def sample_delete_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -957,29 +879,26 @@ async def sample_delete_product_set(): metadata=metadata, ) - async def create_product( - self, - request: Optional[ - Union[product_search_service.CreateProductRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product: Optional[product_search_service.Product] = None, - product_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def create_product(self, + request: Optional[Union[product_search_service.CreateProductRequest, dict]] = None, + *, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. .. code-block:: python @@ -1050,14 +969,10 @@ async def sample_create_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product, product_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1075,14 +990,14 @@ async def sample_create_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1099,23 +1014,20 @@ async def sample_create_product(): # Done; return the response. return response - async def list_products( - self, - request: Optional[ - Union[product_search_service.ListProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsAsyncPager: + async def list_products(self, + request: Optional[Union[product_search_service.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsAsyncPager: r"""Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -1176,14 +1088,10 @@ async def sample_list_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1197,14 +1105,14 @@ async def sample_list_products(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_products - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_products] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1232,20 +1140,19 @@ async def sample_list_products(): # Done; return the response. return response - async def get_product( - self, - request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def get_product(self, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. .. code-block:: python @@ -1301,14 +1208,10 @@ async def sample_get_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1322,14 +1225,14 @@ async def sample_get_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1346,18 +1249,15 @@ async def sample_get_product(): # Done; return the response. return response - async def update_product( - self, - request: Optional[ - Union[product_search_service.UpdateProductRequest, dict] - ] = None, - *, - product: Optional[product_search_service.Product] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def update_product(self, + request: Optional[Union[product_search_service.UpdateProductRequest, dict]] = None, + *, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. @@ -1366,14 +1266,14 @@ async def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. .. code-block:: python @@ -1437,14 +1337,10 @@ async def sample_update_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1460,16 +1356,14 @@ async def sample_update_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.update_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product.name", request.product.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), ) # Validate the universe domain. @@ -1486,17 +1380,14 @@ async def sample_update_product(): # Done; return the response. return response - async def delete_product( - self, - request: Optional[ - Union[product_search_service.DeleteProductRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_product(self, + request: Optional[Union[product_search_service.DeleteProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a product and its reference images. Metadata of the product and all its images will be @@ -1551,14 +1442,10 @@ async def sample_delete_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1572,14 +1459,14 @@ async def sample_delete_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1593,19 +1480,16 @@ async def sample_delete_product(): metadata=metadata, ) - async def create_reference_image( - self, - request: Optional[ - Union[product_search_service.CreateReferenceImageRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - reference_image: Optional[product_search_service.ReferenceImage] = None, - reference_image_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + async def create_reference_image(self, + request: Optional[Union[product_search_service.CreateReferenceImageRequest, dict]] = None, + *, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is @@ -1620,14 +1504,14 @@ async def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. .. code-block:: python @@ -1708,14 +1592,10 @@ async def sample_create_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, reference_image, reference_image_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1733,14 +1613,14 @@ async def sample_create_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1757,17 +1637,14 @@ async def sample_create_reference_image(): # Done; return the response. return response - async def delete_reference_image( - self, - request: Optional[ - Union[product_search_service.DeleteReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_reference_image(self, + request: Optional[Union[product_search_service.DeleteReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a reference image. The image metadata will be deleted right away, but @@ -1825,14 +1702,10 @@ async def sample_delete_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1846,14 +1719,14 @@ async def sample_delete_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1867,24 +1740,21 @@ async def sample_delete_reference_image(): metadata=metadata, ) - async def list_reference_images( - self, - request: Optional[ - Union[product_search_service.ListReferenceImagesRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListReferenceImagesAsyncPager: + async def list_reference_images(self, + request: Optional[Union[product_search_service.ListReferenceImagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListReferenceImagesAsyncPager: r"""Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. .. code-block:: python @@ -1946,14 +1816,10 @@ async def sample_list_reference_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1967,14 +1833,14 @@ async def sample_list_reference_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_reference_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_reference_images] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2002,22 +1868,19 @@ async def sample_list_reference_images(): # Done; return the response. return response - async def get_reference_image( - self, - request: Optional[ - Union[product_search_service.GetReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + async def get_reference_image(self, + request: Optional[Union[product_search_service.GetReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. .. code-block:: python @@ -2076,14 +1939,10 @@ async def sample_get_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2097,14 +1956,14 @@ async def sample_get_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2121,18 +1980,15 @@ async def sample_get_reference_image(): # Done; return the response. return response - async def add_product_to_product_set( - self, - request: Optional[ - Union[product_search_service.AddProductToProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def add_product_to_product_set(self, + request: Optional[Union[product_search_service.AddProductToProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is already present, no change is made. @@ -2140,8 +1996,8 @@ async def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. .. code-block:: python @@ -2203,20 +2059,14 @@ async def sample_add_product_to_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.AddProductToProductSetRequest - ): + if not isinstance(request, product_search_service.AddProductToProductSetRequest): request = product_search_service.AddProductToProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2228,14 +2078,14 @@ async def sample_add_product_to_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.add_product_to_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.add_product_to_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2249,18 +2099,15 @@ async def sample_add_product_to_product_set(): metadata=metadata, ) - async def remove_product_from_product_set( - self, - request: Optional[ - Union[product_search_service.RemoveProductFromProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def remove_product_from_product_set(self, + request: Optional[Union[product_search_service.RemoveProductFromProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Removes a Product from the specified ProductSet. .. code-block:: python @@ -2323,20 +2170,14 @@ async def sample_remove_product_from_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.RemoveProductFromProductSetRequest - ): + if not isinstance(request, product_search_service.RemoveProductFromProductSetRequest): request = product_search_service.RemoveProductFromProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2348,14 +2189,14 @@ async def sample_remove_product_from_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.remove_product_from_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_product_from_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2369,25 +2210,22 @@ async def sample_remove_product_from_product_set(): metadata=metadata, ) - async def list_products_in_product_set( - self, - request: Optional[ - Union[product_search_service.ListProductsInProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsInProductSetAsyncPager: + async def list_products_in_product_set(self, + request: Optional[Union[product_search_service.ListProductsInProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsInProductSetAsyncPager: r"""Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -2451,20 +2289,14 @@ async def sample_list_products_in_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.ListProductsInProductSetRequest - ): + if not isinstance(request, product_search_service.ListProductsInProductSetRequest): request = product_search_service.ListProductsInProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2474,14 +2306,14 @@ async def sample_list_products_in_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_products_in_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_products_in_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2509,20 +2341,15 @@ async def sample_list_products_in_product_set(): # Done; return the response. return response - async def import_product_sets( - self, - request: Optional[ - Union[product_search_service.ImportProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - input_config: Optional[ - product_search_service.ImportProductSetsInputConfig - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def import_product_sets(self, + request: Optional[Union[product_search_service.ImportProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + input_config: Optional[product_search_service.ImportProductSetsInputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. @@ -2612,14 +2439,10 @@ async def sample_import_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2635,14 +2458,14 @@ async def sample_import_product_sets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.import_product_sets - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.import_product_sets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2667,17 +2490,14 @@ async def sample_import_product_sets(): # Done; return the response. return response - async def purge_products( - self, - request: Optional[ - Union[product_search_service.PurgeProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def purge_products(self, + request: Optional[Union[product_search_service.PurgeProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronous API to delete all Products in a ProductSet or all Products that are in no ProductSet. @@ -2776,14 +2596,10 @@ async def sample_purge_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2797,14 +2613,14 @@ async def sample_purge_products(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.purge_products - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.purge_products] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2867,7 +2683,8 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), ) # Validate the universe domain. @@ -2875,11 +2692,7 @@ async def get_operation( # Send the request. response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -2890,13 +2703,12 @@ async def __aenter__(self) -> "ProductSearchAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ProductSearchAsyncClient",) +__all__ = ( + "ProductSearchAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/client.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/client.py index 9419a8f2769c..5eb03cee32e0 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -63,16 +50,15 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1.services.product_search import pagers +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore - -from google.cloud.vision_v1.services.product_search import pagers -from google.cloud.vision_v1.types import geometry, product_search_service - -from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .transports.rest import ProductSearchRestTransport @@ -85,16 +71,14 @@ class ProductSearchClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] _transport_registry["grpc"] = ProductSearchGrpcTransport _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport _transport_registry["rest"] = ProductSearchRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ProductSearchTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProductSearchTransport]: """Returns an appropriate transport class. Args: @@ -117,20 +101,21 @@ class ProductSearchClient(metaclass=ProductSearchClientMeta): """Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to - put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` """ @staticmethod @@ -183,16 +168,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -231,7 +214,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductSearchClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -248,156 +232,95 @@ def transport(self) -> ProductSearchTransport: return self._transport @staticmethod - def product_path( - project: str, - location: str, - product: str, - ) -> str: + def product_path(project: str,location: str,product: str,) -> str: """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + return "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) @staticmethod - def parse_product_path(path: str) -> Dict[str, str]: + def parse_product_path(path: str) -> Dict[str,str]: """Parses a product path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def product_set_path( - project: str, - location: str, - product_set: str, - ) -> str: + def product_set_path(project: str,location: str,product_set: str,) -> str: """Returns a fully-qualified product_set string.""" - return ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + return "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) @staticmethod - def parse_product_set_path(path: str) -> Dict[str, str]: + def parse_product_set_path(path: str) -> Dict[str,str]: """Parses a product_set path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def reference_image_path( - project: str, - location: str, - product: str, - reference_image: str, - ) -> str: + def reference_image_path(project: str,location: str,product: str,reference_image: str,) -> str: """Returns a fully-qualified reference_image string.""" - return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( - project=project, - location=location, - product=product, - reference_image=reference_image, - ) + return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format(project=project, location=location, product=product, reference_image=reference_image, ) @staticmethod - def parse_reference_image_path(path: str) -> Dict[str, str]: + def parse_reference_image_path(path: str) -> Dict[str,str]: """Parses a reference_image path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -429,18 +352,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ProductSearchClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -453,9 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -480,9 +397,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -505,9 +420,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -523,25 +436,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ProductSearchClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ProductSearchClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -577,18 +482,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -621,16 +523,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the product search client. Args: @@ -685,24 +583,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ProductSearchClient._read_environment_variables() - self._client_cert_source = ProductSearchClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ProductSearchClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ProductSearchClient._read_environment_variables() + self._client_cert_source = ProductSearchClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProductSearchClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -713,9 +601,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -724,10 +610,8 @@ def __init__( if transport_provided: # transport is a ProductSearchTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -736,29 +620,20 @@ def __init__( self._transport = cast(ProductSearchTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ProductSearchClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ProductSearchClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ProductSearchTransport], Callable[..., ProductSearchTransport] - ] = ( + transport_init: Union[Type[ProductSearchTransport], Callable[..., ProductSearchTransport]] = ( ProductSearchClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ProductSearchTransport], transport) @@ -777,47 +652,36 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1.ProductSearchClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1.ProductSearch", "credentialsType": None, - }, + } ) - def create_product_set( - self, - request: Optional[ - Union[product_search_service.CreateProductSetRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product_set: Optional[product_search_service.ProductSet] = None, - product_set_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def create_product_set(self, + request: Optional[Union[product_search_service.CreateProductSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. .. code-block:: python @@ -893,14 +757,10 @@ def sample_create_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product_set, product_set_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -922,7 +782,9 @@ def sample_create_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -939,23 +801,20 @@ def sample_create_product_set(): # Done; return the response. return response - def list_product_sets( - self, - request: Optional[ - Union[product_search_service.ListProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductSetsPager: + def list_product_sets(self, + request: Optional[Union[product_search_service.ListProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductSetsPager: r"""Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. .. code-block:: python @@ -1016,14 +875,10 @@ def sample_list_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1041,7 +896,9 @@ def sample_list_product_sets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1069,22 +926,19 @@ def sample_list_product_sets(): # Done; return the response. return response - def get_product_set( - self, - request: Optional[ - Union[product_search_service.GetProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def get_product_set(self, + request: Optional[Union[product_search_service.GetProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -1145,14 +999,10 @@ def sample_get_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1170,7 +1020,9 @@ def sample_get_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1187,27 +1039,24 @@ def sample_get_product_set(): # Done; return the response. return response - def update_product_set( - self, - request: Optional[ - Union[product_search_service.UpdateProductSetRequest, dict] - ] = None, - *, - product_set: Optional[product_search_service.ProductSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def update_product_set(self, + request: Optional[Union[product_search_service.UpdateProductSetRequest, dict]] = None, + *, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. .. code-block:: python @@ -1274,14 +1123,10 @@ def sample_update_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product_set, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1301,9 +1146,9 @@ def sample_update_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product_set.name", request.product_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product_set.name", request.product_set.name), + )), ) # Validate the universe domain. @@ -1320,17 +1165,14 @@ def sample_update_product_set(): # Done; return the response. return response - def delete_product_set( - self, - request: Optional[ - Union[product_search_service.DeleteProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_product_set(self, + request: Optional[Union[product_search_service.DeleteProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a ProductSet. Products and ReferenceImages in the ProductSet are not deleted. @@ -1384,14 +1226,10 @@ def sample_delete_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1409,7 +1247,9 @@ def sample_delete_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1423,29 +1263,26 @@ def sample_delete_product_set(): metadata=metadata, ) - def create_product( - self, - request: Optional[ - Union[product_search_service.CreateProductRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product: Optional[product_search_service.Product] = None, - product_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def create_product(self, + request: Optional[Union[product_search_service.CreateProductRequest, dict]] = None, + *, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. .. code-block:: python @@ -1516,14 +1353,10 @@ def sample_create_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product, product_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1545,7 +1378,9 @@ def sample_create_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1562,23 +1397,20 @@ def sample_create_product(): # Done; return the response. return response - def list_products( - self, - request: Optional[ - Union[product_search_service.ListProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsPager: + def list_products(self, + request: Optional[Union[product_search_service.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsPager: r"""Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -1639,14 +1471,10 @@ def sample_list_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1664,7 +1492,9 @@ def sample_list_products(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1692,20 +1522,19 @@ def sample_list_products(): # Done; return the response. return response - def get_product( - self, - request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def get_product(self, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. .. code-block:: python @@ -1761,14 +1590,10 @@ def sample_get_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1786,7 +1611,9 @@ def sample_get_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1803,18 +1630,15 @@ def sample_get_product(): # Done; return the response. return response - def update_product( - self, - request: Optional[ - Union[product_search_service.UpdateProductRequest, dict] - ] = None, - *, - product: Optional[product_search_service.Product] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def update_product(self, + request: Optional[Union[product_search_service.UpdateProductRequest, dict]] = None, + *, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. @@ -1823,14 +1647,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. .. code-block:: python @@ -1894,14 +1718,10 @@ def sample_update_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1921,9 +1741,9 @@ def sample_update_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product.name", request.product.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), ) # Validate the universe domain. @@ -1940,17 +1760,14 @@ def sample_update_product(): # Done; return the response. return response - def delete_product( - self, - request: Optional[ - Union[product_search_service.DeleteProductRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_product(self, + request: Optional[Union[product_search_service.DeleteProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a product and its reference images. Metadata of the product and all its images will be @@ -2005,14 +1822,10 @@ def sample_delete_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2030,7 +1843,9 @@ def sample_delete_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2044,19 +1859,16 @@ def sample_delete_product(): metadata=metadata, ) - def create_reference_image( - self, - request: Optional[ - Union[product_search_service.CreateReferenceImageRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - reference_image: Optional[product_search_service.ReferenceImage] = None, - reference_image_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def create_reference_image(self, + request: Optional[Union[product_search_service.CreateReferenceImageRequest, dict]] = None, + *, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is @@ -2071,14 +1883,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. .. code-block:: python @@ -2159,14 +1971,10 @@ def sample_create_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, reference_image, reference_image_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2188,7 +1996,9 @@ def sample_create_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2205,17 +2015,14 @@ def sample_create_reference_image(): # Done; return the response. return response - def delete_reference_image( - self, - request: Optional[ - Union[product_search_service.DeleteReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_reference_image(self, + request: Optional[Union[product_search_service.DeleteReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a reference image. The image metadata will be deleted right away, but @@ -2273,14 +2080,10 @@ def sample_delete_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2298,7 +2101,9 @@ def sample_delete_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2312,24 +2117,21 @@ def sample_delete_reference_image(): metadata=metadata, ) - def list_reference_images( - self, - request: Optional[ - Union[product_search_service.ListReferenceImagesRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListReferenceImagesPager: + def list_reference_images(self, + request: Optional[Union[product_search_service.ListReferenceImagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListReferenceImagesPager: r"""Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. .. code-block:: python @@ -2391,14 +2193,10 @@ def sample_list_reference_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2416,7 +2214,9 @@ def sample_list_reference_images(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2444,22 +2244,19 @@ def sample_list_reference_images(): # Done; return the response. return response - def get_reference_image( - self, - request: Optional[ - Union[product_search_service.GetReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def get_reference_image(self, + request: Optional[Union[product_search_service.GetReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. .. code-block:: python @@ -2518,14 +2315,10 @@ def sample_get_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2543,7 +2336,9 @@ def sample_get_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2560,18 +2355,15 @@ def sample_get_reference_image(): # Done; return the response. return response - def add_product_to_product_set( - self, - request: Optional[ - Union[product_search_service.AddProductToProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def add_product_to_product_set(self, + request: Optional[Union[product_search_service.AddProductToProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is already present, no change is made. @@ -2579,8 +2371,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. .. code-block:: python @@ -2642,20 +2434,14 @@ def sample_add_product_to_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.AddProductToProductSetRequest - ): + if not isinstance(request, product_search_service.AddProductToProductSetRequest): request = product_search_service.AddProductToProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2666,14 +2452,14 @@ def sample_add_product_to_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.add_product_to_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.add_product_to_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2687,18 +2473,15 @@ def sample_add_product_to_product_set(): metadata=metadata, ) - def remove_product_from_product_set( - self, - request: Optional[ - Union[product_search_service.RemoveProductFromProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def remove_product_from_product_set(self, + request: Optional[Union[product_search_service.RemoveProductFromProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Removes a Product from the specified ProductSet. .. code-block:: python @@ -2761,20 +2544,14 @@ def sample_remove_product_from_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.RemoveProductFromProductSetRequest - ): + if not isinstance(request, product_search_service.RemoveProductFromProductSetRequest): request = product_search_service.RemoveProductFromProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2785,14 +2562,14 @@ def sample_remove_product_from_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.remove_product_from_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.remove_product_from_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2806,25 +2583,22 @@ def sample_remove_product_from_product_set(): metadata=metadata, ) - def list_products_in_product_set( - self, - request: Optional[ - Union[product_search_service.ListProductsInProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsInProductSetPager: + def list_products_in_product_set(self, + request: Optional[Union[product_search_service.ListProductsInProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsInProductSetPager: r"""Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -2888,20 +2662,14 @@ def sample_list_products_in_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.ListProductsInProductSetRequest - ): + if not isinstance(request, product_search_service.ListProductsInProductSetRequest): request = product_search_service.ListProductsInProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2910,14 +2678,14 @@ def sample_list_products_in_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_products_in_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.list_products_in_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2945,20 +2713,15 @@ def sample_list_products_in_product_set(): # Done; return the response. return response - def import_product_sets( - self, - request: Optional[ - Union[product_search_service.ImportProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - input_config: Optional[ - product_search_service.ImportProductSetsInputConfig - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def import_product_sets(self, + request: Optional[Union[product_search_service.ImportProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + input_config: Optional[product_search_service.ImportProductSetsInputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. @@ -3048,14 +2811,10 @@ def sample_import_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3075,7 +2834,9 @@ def sample_import_product_sets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3100,17 +2861,14 @@ def sample_import_product_sets(): # Done; return the response. return response - def purge_products( - self, - request: Optional[ - Union[product_search_service.PurgeProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def purge_products(self, + request: Optional[Union[product_search_service.PurgeProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronous API to delete all Products in a ProductSet or all Products that are in no ProductSet. @@ -3209,14 +2967,10 @@ def sample_purge_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3234,7 +2988,9 @@ def sample_purge_products(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3310,7 +3066,8 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), ) # Validate the universe domain. @@ -3319,11 +3076,7 @@ def get_operation( try: # Send the request. response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -3332,11 +3085,18 @@ def get_operation( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ProductSearchClient",) +__all__ = ( + "ProductSearchClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/pagers.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/pagers.py index 685cb392cf54..4cd45f704986 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/pagers.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/pagers.py @@ -13,27 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import ( - Any, - AsyncIterator, - Awaitable, - Callable, - Iterator, - Optional, - Sequence, - Tuple, - Union, -) - from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import retry_async as retries_async - +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[ - retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None - ] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore @@ -58,17 +44,14 @@ class ListProductSetsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductSetsResponse], - request: product_search_service.ListProductSetsRequest, - response: product_search_service.ListProductSetsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductSetsResponse], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -101,12 +84,7 @@ def pages(self) -> Iterator[product_search_service.ListProductSetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.ProductSet]: @@ -114,7 +92,7 @@ def __iter__(self) -> Iterator[product_search_service.ProductSet]: yield from page.product_sets def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductSetsAsyncPager: @@ -134,19 +112,14 @@ class ListProductSetsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListProductSetsResponse] - ], - request: product_search_service.ListProductSetsRequest, - response: product_search_service.ListProductSetsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductSetsResponse]], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -175,20 +148,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListProductSetsResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListProductSetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.ProductSet]: async def async_generator(): async for page in self.pages: @@ -198,7 +163,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsPager: @@ -218,17 +183,14 @@ class ListProductsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductsResponse], - request: product_search_service.ListProductsRequest, - response: product_search_service.ListProductsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductsResponse], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -261,12 +223,7 @@ def pages(self) -> Iterator[product_search_service.ListProductsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.Product]: @@ -274,7 +231,7 @@ def __iter__(self) -> Iterator[product_search_service.Product]: yield from page.products def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsAsyncPager: @@ -294,17 +251,14 @@ class ListProductsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], - request: product_search_service.ListProductsRequest, - response: product_search_service.ListProductsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -337,14 +291,8 @@ async def pages(self) -> AsyncIterator[product_search_service.ListProductsRespon yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.Product]: async def async_generator(): async for page in self.pages: @@ -354,7 +302,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListReferenceImagesPager: @@ -374,17 +322,14 @@ class ListReferenceImagesPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListReferenceImagesResponse], - request: product_search_service.ListReferenceImagesRequest, - response: product_search_service.ListReferenceImagesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListReferenceImagesResponse], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -417,12 +362,7 @@ def pages(self) -> Iterator[product_search_service.ListReferenceImagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.ReferenceImage]: @@ -430,7 +370,7 @@ def __iter__(self) -> Iterator[product_search_service.ReferenceImage]: yield from page.reference_images def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListReferenceImagesAsyncPager: @@ -450,19 +390,14 @@ class ListReferenceImagesAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListReferenceImagesResponse] - ], - request: product_search_service.ListReferenceImagesRequest, - response: product_search_service.ListReferenceImagesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListReferenceImagesResponse]], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -491,20 +426,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListReferenceImagesResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListReferenceImagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.ReferenceImage]: async def async_generator(): async for page in self.pages: @@ -514,7 +441,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsInProductSetPager: @@ -534,17 +461,14 @@ class ListProductsInProductSetPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductsInProductSetResponse], - request: product_search_service.ListProductsInProductSetRequest, - response: product_search_service.ListProductsInProductSetResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductsInProductSetResponse], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -573,18 +497,11 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages( - self, - ) -> Iterator[product_search_service.ListProductsInProductSetResponse]: + def pages(self) -> Iterator[product_search_service.ListProductsInProductSetResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.Product]: @@ -592,7 +509,7 @@ def __iter__(self) -> Iterator[product_search_service.Product]: yield from page.products def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsInProductSetAsyncPager: @@ -612,19 +529,14 @@ class ListProductsInProductSetAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListProductsInProductSetResponse] - ], - request: product_search_service.ListProductsInProductSetRequest, - response: product_search_service.ListProductsInProductSetResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductsInProductSetResponse]], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -653,20 +565,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListProductsInProductSetResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListProductsInProductSetResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.Product]: async def async_generator(): async for page in self.pages: @@ -676,4 +580,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/__init__.py index e3bd7adc48d8..f5f6aac78c26 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ProductSearchTransport from .grpc import ProductSearchGrpcTransport from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport -from .rest import ProductSearchRestInterceptor, ProductSearchRestTransport +from .rest import ProductSearchRestTransport +from .rest import ProductSearchRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] -_transport_registry["grpc"] = ProductSearchGrpcTransport -_transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport -_transport_registry["rest"] = ProductSearchRestTransport +_transport_registry['grpc'] = ProductSearchGrpcTransport +_transport_registry['grpc_asyncio'] = ProductSearchGrpcAsyncIOTransport +_transport_registry['rest'] = ProductSearchRestTransport __all__ = ( - "ProductSearchTransport", - "ProductSearchGrpcTransport", - "ProductSearchGrpcAsyncIOTransport", - "ProductSearchRestTransport", - "ProductSearchRestInterceptor", + 'ProductSearchTransport', + 'ProductSearchGrpcTransport', + 'ProductSearchGrpcAsyncIOTransport', + 'ProductSearchRestTransport', + 'ProductSearchRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/base.py index 68aa99040a97..ea7b1e807892 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/base.py @@ -16,23 +16,23 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.protobuf import empty_pb2 # type: ignore -from google.cloud.vision_v1 import gapic_version as package_version from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -42,25 +42,24 @@ class ProductSearchTransport(abc.ABC): """Abstract transport class for ProductSearch.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -87,8 +86,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -97,38 +94,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -144,7 +134,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -216,7 +207,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -288,7 +280,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -390,7 +383,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -402,7 +396,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -413,14 +408,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -430,207 +425,174 @@ def operations_client(self): raise NotImplementedError() @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - Union[ - product_search_service.ListProductSetsResponse, - Awaitable[product_search_service.ListProductSetsResponse], - ], - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + Union[ + product_search_service.ListProductSetsResponse, + Awaitable[product_search_service.ListProductSetsResponse] + ]]: raise NotImplementedError() @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def delete_product_set( - self, - ) -> Callable[ - [product_search_service.DeleteProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - Union[ - product_search_service.ListProductsResponse, - Awaitable[product_search_service.ListProductsResponse], - ], - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + Union[ + product_search_service.ListProductsResponse, + Awaitable[product_search_service.ListProductsResponse] + ]]: raise NotImplementedError() @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def delete_product( - self, - ) -> Callable[ - [product_search_service.DeleteProductRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - Union[ - product_search_service.ReferenceImage, - Awaitable[product_search_service.ReferenceImage], - ], - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Union[ + product_search_service.ReferenceImage, + Awaitable[product_search_service.ReferenceImage] + ]]: raise NotImplementedError() @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - Union[ - product_search_service.ListReferenceImagesResponse, - Awaitable[product_search_service.ListReferenceImagesResponse], - ], - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Union[ + product_search_service.ListReferenceImagesResponse, + Awaitable[product_search_service.ListReferenceImagesResponse] + ]]: raise NotImplementedError() @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - Union[ - product_search_service.ReferenceImage, - Awaitable[product_search_service.ReferenceImage], - ], - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Union[ + product_search_service.ReferenceImage, + Awaitable[product_search_service.ReferenceImage] + ]]: raise NotImplementedError() @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - Union[ - product_search_service.ListProductsInProductSetResponse, - Awaitable[product_search_service.ListProductsInProductSetResponse], - ], - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Union[ + product_search_service.ListProductsInProductSetResponse, + Awaitable[product_search_service.ListProductsInProductSetResponse] + ]]: raise NotImplementedError() @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -647,4 +609,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ProductSearchTransport",) +__all__ = ( + 'ProductSearchTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc.py index e75e8b70e142..f46d22405c32 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc.py @@ -16,27 +16,28 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +47,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +68,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,11 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -99,7 +94,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,20 +110,21 @@ class ProductSearchGrpcTransport(ProductSearchTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to - put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -137,26 +133,23 @@ class ProductSearchGrpcTransport(ProductSearchTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -280,23 +273,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -332,12 +321,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -357,20 +347,17 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - product_search_service.ProductSet, - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the create product set method over gRPC. Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. Returns: Callable[[~.CreateProductSetRequest], @@ -382,29 +369,26 @@ def create_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product_set" not in self._stubs: - self._stubs["create_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateProductSet", + if 'create_product_set' not in self._stubs: + self._stubs['create_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/CreateProductSet', request_serializer=product_search_service.CreateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["create_product_set"] + return self._stubs['create_product_set'] @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - product_search_service.ListProductSetsResponse, - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse]: r"""Return a callable for the list product sets method over gRPC. Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. Returns: Callable[[~.ListProductSetsRequest], @@ -416,27 +400,25 @@ def list_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_product_sets" not in self._stubs: - self._stubs["list_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProductSets", + if 'list_product_sets' not in self._stubs: + self._stubs['list_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListProductSets', request_serializer=product_search_service.ListProductSetsRequest.serialize, response_deserializer=product_search_service.ListProductSetsResponse.deserialize, ) - return self._stubs["list_product_sets"] + return self._stubs['list_product_sets'] @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], product_search_service.ProductSet - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the get product set method over gRPC. Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.GetProductSetRequest], @@ -448,21 +430,18 @@ def get_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product_set" not in self._stubs: - self._stubs["get_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetProductSet", + if 'get_product_set' not in self._stubs: + self._stubs['get_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/GetProductSet', request_serializer=product_search_service.GetProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["get_product_set"] + return self._stubs['get_product_set'] @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - product_search_service.ProductSet, - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the update product set method over gRPC. Makes changes to a ProductSet resource. Only display_name can be @@ -470,10 +449,10 @@ def update_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. Returns: Callable[[~.UpdateProductSetRequest], @@ -485,18 +464,18 @@ def update_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product_set" not in self._stubs: - self._stubs["update_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/UpdateProductSet", + if 'update_product_set' not in self._stubs: + self._stubs['update_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/UpdateProductSet', request_serializer=product_search_service.UpdateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["update_product_set"] + return self._stubs['update_product_set'] @property - def delete_product_set( - self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. Products and @@ -515,32 +494,30 @@ def delete_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product_set" not in self._stubs: - self._stubs["delete_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteProductSet", + if 'delete_product_set' not in self._stubs: + self._stubs['delete_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/DeleteProductSet', request_serializer=product_search_service.DeleteProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product_set"] + return self._stubs['delete_product_set'] @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], product_search_service.Product - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + product_search_service.Product]: r"""Return a callable for the create product method over gRPC. Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. Returns: Callable[[~.CreateProductRequest], @@ -552,29 +529,26 @@ def create_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product" not in self._stubs: - self._stubs["create_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateProduct", + if 'create_product' not in self._stubs: + self._stubs['create_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/CreateProduct', request_serializer=product_search_service.CreateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["create_product"] + return self._stubs['create_product'] @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - product_search_service.ListProductsResponse, - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse]: r"""Return a callable for the list products method over gRPC. Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsRequest], @@ -586,27 +560,25 @@ def list_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products" not in self._stubs: - self._stubs["list_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProducts", + if 'list_products' not in self._stubs: + self._stubs['list_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListProducts', request_serializer=product_search_service.ListProductsRequest.serialize, response_deserializer=product_search_service.ListProductsResponse.deserialize, ) - return self._stubs["list_products"] + return self._stubs['list_products'] @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], product_search_service.Product - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + product_search_service.Product]: r"""Return a callable for the get product method over gRPC. Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. Returns: Callable[[~.GetProductRequest], @@ -618,20 +590,18 @@ def get_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product" not in self._stubs: - self._stubs["get_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetProduct", + if 'get_product' not in self._stubs: + self._stubs['get_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/GetProduct', request_serializer=product_search_service.GetProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["get_product"] + return self._stubs['get_product'] @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], product_search_service.Product - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + product_search_service.Product]: r"""Return a callable for the update product method over gRPC. Makes changes to a Product resource. Only the ``display_name``, @@ -642,14 +612,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. Returns: Callable[[~.UpdateProductRequest], @@ -661,18 +631,18 @@ def update_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product" not in self._stubs: - self._stubs["update_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/UpdateProduct", + if 'update_product' not in self._stubs: + self._stubs['update_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/UpdateProduct', request_serializer=product_search_service.UpdateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["update_product"] + return self._stubs['update_product'] @property - def delete_product( - self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + empty_pb2.Empty]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference @@ -692,21 +662,18 @@ def delete_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product" not in self._stubs: - self._stubs["delete_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteProduct", + if 'delete_product' not in self._stubs: + self._stubs['delete_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/DeleteProduct', request_serializer=product_search_service.DeleteProductRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product"] + return self._stubs['delete_product'] @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage]: r"""Return a callable for the create reference image method over gRPC. Creates and returns a new ReferenceImage resource. @@ -723,14 +690,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. Returns: Callable[[~.CreateReferenceImageRequest], @@ -742,20 +709,18 @@ def create_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_reference_image" not in self._stubs: - self._stubs["create_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateReferenceImage", + if 'create_reference_image' not in self._stubs: + self._stubs['create_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/CreateReferenceImage', request_serializer=product_search_service.CreateReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["create_reference_image"] + return self._stubs['create_reference_image'] @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + empty_pb2.Empty]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -777,30 +742,27 @@ def delete_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_reference_image" not in self._stubs: - self._stubs["delete_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage", + if 'delete_reference_image' not in self._stubs: + self._stubs['delete_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage', request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_reference_image"] + return self._stubs['delete_reference_image'] @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - product_search_service.ListReferenceImagesResponse, - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse]: r"""Return a callable for the list reference images method over gRPC. Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. Returns: Callable[[~.ListReferenceImagesRequest], @@ -812,28 +774,25 @@ def list_reference_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_reference_images" not in self._stubs: - self._stubs["list_reference_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListReferenceImages", + if 'list_reference_images' not in self._stubs: + self._stubs['list_reference_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListReferenceImages', request_serializer=product_search_service.ListReferenceImagesRequest.serialize, response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, ) - return self._stubs["list_reference_images"] + return self._stubs['list_reference_images'] @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage]: r"""Return a callable for the get reference image method over gRPC. Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. Returns: Callable[[~.GetReferenceImageRequest], @@ -845,20 +804,18 @@ def get_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_reference_image" not in self._stubs: - self._stubs["get_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetReferenceImage", + if 'get_reference_image' not in self._stubs: + self._stubs['get_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/GetReferenceImage', request_serializer=product_search_service.GetReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["get_reference_image"] + return self._stubs['get_reference_image'] @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], empty_pb2.Empty - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the add product to product set method over gRPC. Adds a Product to the specified ProductSet. If the Product is @@ -868,8 +825,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. Returns: Callable[[~.AddProductToProductSetRequest], @@ -881,22 +838,18 @@ def add_product_to_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "add_product_to_product_set" not in self._stubs: - self._stubs[ - "add_product_to_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/AddProductToProductSet", + if 'add_product_to_product_set' not in self._stubs: + self._stubs['add_product_to_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/AddProductToProductSet', request_serializer=product_search_service.AddProductToProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["add_product_to_product_set"] + return self._stubs['add_product_to_product_set'] @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the remove product from product set method over gRPC. @@ -912,23 +865,18 @@ def remove_product_from_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "remove_product_from_product_set" not in self._stubs: - self._stubs[ - "remove_product_from_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet", + if 'remove_product_from_product_set' not in self._stubs: + self._stubs['remove_product_from_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet', request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["remove_product_from_product_set"] + return self._stubs['remove_product_from_product_set'] @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - product_search_service.ListProductsInProductSetResponse, - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse]: r"""Return a callable for the list products in product set method over gRPC. Lists the Products in a ProductSet, in an unspecified order. If @@ -937,8 +885,8 @@ def list_products_in_product_set( Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsInProductSetRequest], @@ -950,22 +898,18 @@ def list_products_in_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products_in_product_set" not in self._stubs: - self._stubs[ - "list_products_in_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet", + if 'list_products_in_product_set' not in self._stubs: + self._stubs['list_products_in_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet', request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, ) - return self._stubs["list_products_in_product_set"] + return self._stubs['list_products_in_product_set'] @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations_pb2.Operation - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + operations_pb2.Operation]: r"""Return a callable for the import product sets method over gRPC. Asynchronous API that imports a list of reference images to @@ -991,20 +935,18 @@ def import_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_product_sets" not in self._stubs: - self._stubs["import_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ImportProductSets", + if 'import_product_sets' not in self._stubs: + self._stubs['import_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ImportProductSets', request_serializer=product_search_service.ImportProductSetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_product_sets"] + return self._stubs['import_product_sets'] @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], operations_pb2.Operation - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + operations_pb2.Operation]: r"""Return a callable for the purge products method over gRPC. Asynchronous API to delete all Products in a ProductSet or all @@ -1045,13 +987,13 @@ def purge_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "purge_products" not in self._stubs: - self._stubs["purge_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/PurgeProducts", + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/PurgeProducts', request_serializer=product_search_service.PurgeProductsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["purge_products"] + return self._stubs['purge_products'] def close(self): self._logged_channel.close() @@ -1060,7 +1002,8 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1078,4 +1021,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ProductSearchGrpcTransport",) +__all__ = ( + 'ProductSearchGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py index 2d25de74b853..e02e6c3b3ddb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py @@ -15,32 +15,33 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .grpc import ProductSearchGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -48,13 +49,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -75,7 +72,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -86,11 +83,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +98,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -121,20 +114,21 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to - put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -148,15 +142,13 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -187,26 +179,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -332,9 +322,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -365,20 +353,17 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the create product set method over gRPC. Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. Returns: Callable[[~.CreateProductSetRequest], @@ -390,29 +375,26 @@ def create_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product_set" not in self._stubs: - self._stubs["create_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateProductSet", + if 'create_product_set' not in self._stubs: + self._stubs['create_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/CreateProductSet', request_serializer=product_search_service.CreateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["create_product_set"] + return self._stubs['create_product_set'] @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - Awaitable[product_search_service.ListProductSetsResponse], - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + Awaitable[product_search_service.ListProductSetsResponse]]: r"""Return a callable for the list product sets method over gRPC. Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. Returns: Callable[[~.ListProductSetsRequest], @@ -424,28 +406,25 @@ def list_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_product_sets" not in self._stubs: - self._stubs["list_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProductSets", + if 'list_product_sets' not in self._stubs: + self._stubs['list_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListProductSets', request_serializer=product_search_service.ListProductSetsRequest.serialize, response_deserializer=product_search_service.ListProductSetsResponse.deserialize, ) - return self._stubs["list_product_sets"] + return self._stubs['list_product_sets'] @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the get product set method over gRPC. Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.GetProductSetRequest], @@ -457,21 +436,18 @@ def get_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product_set" not in self._stubs: - self._stubs["get_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetProductSet", + if 'get_product_set' not in self._stubs: + self._stubs['get_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/GetProductSet', request_serializer=product_search_service.GetProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["get_product_set"] + return self._stubs['get_product_set'] @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the update product set method over gRPC. Makes changes to a ProductSet resource. Only display_name can be @@ -479,10 +455,10 @@ def update_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. Returns: Callable[[~.UpdateProductSetRequest], @@ -494,20 +470,18 @@ def update_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product_set" not in self._stubs: - self._stubs["update_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/UpdateProductSet", + if 'update_product_set' not in self._stubs: + self._stubs['update_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/UpdateProductSet', request_serializer=product_search_service.UpdateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["update_product_set"] + return self._stubs['update_product_set'] @property - def delete_product_set( - self, - ) -> Callable[ - [product_search_service.DeleteProductSetRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. Products and @@ -526,33 +500,30 @@ def delete_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product_set" not in self._stubs: - self._stubs["delete_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteProductSet", + if 'delete_product_set' not in self._stubs: + self._stubs['delete_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/DeleteProductSet', request_serializer=product_search_service.DeleteProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product_set"] + return self._stubs['delete_product_set'] @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], - Awaitable[product_search_service.Product], - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the create product method over gRPC. Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. Returns: Callable[[~.CreateProductRequest], @@ -564,29 +535,26 @@ def create_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product" not in self._stubs: - self._stubs["create_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateProduct", + if 'create_product' not in self._stubs: + self._stubs['create_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/CreateProduct', request_serializer=product_search_service.CreateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["create_product"] + return self._stubs['create_product'] @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - Awaitable[product_search_service.ListProductsResponse], - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + Awaitable[product_search_service.ListProductsResponse]]: r"""Return a callable for the list products method over gRPC. Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsRequest], @@ -598,28 +566,25 @@ def list_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products" not in self._stubs: - self._stubs["list_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProducts", + if 'list_products' not in self._stubs: + self._stubs['list_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListProducts', request_serializer=product_search_service.ListProductsRequest.serialize, response_deserializer=product_search_service.ListProductsResponse.deserialize, ) - return self._stubs["list_products"] + return self._stubs['list_products'] @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], - Awaitable[product_search_service.Product], - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the get product method over gRPC. Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. Returns: Callable[[~.GetProductRequest], @@ -631,21 +596,18 @@ def get_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product" not in self._stubs: - self._stubs["get_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetProduct", + if 'get_product' not in self._stubs: + self._stubs['get_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/GetProduct', request_serializer=product_search_service.GetProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["get_product"] + return self._stubs['get_product'] @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], - Awaitable[product_search_service.Product], - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the update product method over gRPC. Makes changes to a Product resource. Only the ``display_name``, @@ -656,14 +618,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. Returns: Callable[[~.UpdateProductRequest], @@ -675,20 +637,18 @@ def update_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product" not in self._stubs: - self._stubs["update_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/UpdateProduct", + if 'update_product' not in self._stubs: + self._stubs['update_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/UpdateProduct', request_serializer=product_search_service.UpdateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["update_product"] + return self._stubs['update_product'] @property - def delete_product( - self, - ) -> Callable[ - [product_search_service.DeleteProductRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference @@ -708,21 +668,18 @@ def delete_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product" not in self._stubs: - self._stubs["delete_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteProduct", + if 'delete_product' not in self._stubs: + self._stubs['delete_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/DeleteProduct', request_serializer=product_search_service.DeleteProductRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product"] + return self._stubs['delete_product'] @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - Awaitable[product_search_service.ReferenceImage], - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage]]: r"""Return a callable for the create reference image method over gRPC. Creates and returns a new ReferenceImage resource. @@ -739,14 +696,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. Returns: Callable[[~.CreateReferenceImageRequest], @@ -758,20 +715,18 @@ def create_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_reference_image" not in self._stubs: - self._stubs["create_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateReferenceImage", + if 'create_reference_image' not in self._stubs: + self._stubs['create_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/CreateReferenceImage', request_serializer=product_search_service.CreateReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["create_reference_image"] + return self._stubs['create_reference_image'] @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -793,30 +748,27 @@ def delete_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_reference_image" not in self._stubs: - self._stubs["delete_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage", + if 'delete_reference_image' not in self._stubs: + self._stubs['delete_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage', request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_reference_image"] + return self._stubs['delete_reference_image'] @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - Awaitable[product_search_service.ListReferenceImagesResponse], - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Awaitable[product_search_service.ListReferenceImagesResponse]]: r"""Return a callable for the list reference images method over gRPC. Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. Returns: Callable[[~.ListReferenceImagesRequest], @@ -828,28 +780,25 @@ def list_reference_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_reference_images" not in self._stubs: - self._stubs["list_reference_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListReferenceImages", + if 'list_reference_images' not in self._stubs: + self._stubs['list_reference_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListReferenceImages', request_serializer=product_search_service.ListReferenceImagesRequest.serialize, response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, ) - return self._stubs["list_reference_images"] + return self._stubs['list_reference_images'] @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - Awaitable[product_search_service.ReferenceImage], - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage]]: r"""Return a callable for the get reference image method over gRPC. Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. Returns: Callable[[~.GetReferenceImageRequest], @@ -861,21 +810,18 @@ def get_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_reference_image" not in self._stubs: - self._stubs["get_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetReferenceImage", + if 'get_reference_image' not in self._stubs: + self._stubs['get_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/GetReferenceImage', request_serializer=product_search_service.GetReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["get_reference_image"] + return self._stubs['get_reference_image'] @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], - Awaitable[empty_pb2.Empty], - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the add product to product set method over gRPC. Adds a Product to the specified ProductSet. If the Product is @@ -885,8 +831,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. Returns: Callable[[~.AddProductToProductSetRequest], @@ -898,23 +844,18 @@ def add_product_to_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "add_product_to_product_set" not in self._stubs: - self._stubs[ - "add_product_to_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/AddProductToProductSet", + if 'add_product_to_product_set' not in self._stubs: + self._stubs['add_product_to_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/AddProductToProductSet', request_serializer=product_search_service.AddProductToProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["add_product_to_product_set"] + return self._stubs['add_product_to_product_set'] @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], - Awaitable[empty_pb2.Empty], - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the remove product from product set method over gRPC. @@ -930,23 +871,18 @@ def remove_product_from_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "remove_product_from_product_set" not in self._stubs: - self._stubs[ - "remove_product_from_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet", + if 'remove_product_from_product_set' not in self._stubs: + self._stubs['remove_product_from_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet', request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["remove_product_from_product_set"] + return self._stubs['remove_product_from_product_set'] @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - Awaitable[product_search_service.ListProductsInProductSetResponse], - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Awaitable[product_search_service.ListProductsInProductSetResponse]]: r"""Return a callable for the list products in product set method over gRPC. Lists the Products in a ProductSet, in an unspecified order. If @@ -955,8 +891,8 @@ def list_products_in_product_set( Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsInProductSetRequest], @@ -968,23 +904,18 @@ def list_products_in_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products_in_product_set" not in self._stubs: - self._stubs[ - "list_products_in_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet", + if 'list_products_in_product_set' not in self._stubs: + self._stubs['list_products_in_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet', request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, ) - return self._stubs["list_products_in_product_set"] + return self._stubs['list_products_in_product_set'] @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], - Awaitable[operations_pb2.Operation], - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import product sets method over gRPC. Asynchronous API that imports a list of reference images to @@ -1010,21 +941,18 @@ def import_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_product_sets" not in self._stubs: - self._stubs["import_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ImportProductSets", + if 'import_product_sets' not in self._stubs: + self._stubs['import_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/ImportProductSets', request_serializer=product_search_service.ImportProductSetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_product_sets"] + return self._stubs['import_product_sets'] @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], - Awaitable[operations_pb2.Operation], - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the purge products method over gRPC. Asynchronous API to delete all Products in a ProductSet or all @@ -1065,16 +993,16 @@ def purge_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "purge_products" not in self._stubs: - self._stubs["purge_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/PurgeProducts", + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1.ProductSearch/PurgeProducts', request_serializer=product_search_service.PurgeProductsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["purge_products"] + return self._stubs['purge_products'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.create_product_set: self._wrap_method( self.create_product_set, @@ -1082,7 +1010,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1154,7 +1083,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1226,7 +1156,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1328,7 +1259,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1340,7 +1272,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1369,7 +1302,8 @@ def kind(self) -> str: def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC.""" + r"""Return a callable for the get_operation method over gRPC. + """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -1383,4 +1317,6 @@ def get_operation( return self._stubs["get_operation"] -__all__ = ("ProductSearchGrpcAsyncIOTransport",) +__all__ = ( + 'ProductSearchGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest.py index 65c13eb81d75..e3767dd63b7d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest.py @@ -13,27 +13,34 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf -from google.protobuf import empty_pb2 # type: ignore + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1.types import product_search_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseProductSearchRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,7 +49,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -211,15 +217,7 @@ def post_update_product_set(self, response): """ - - def pre_add_product_to_product_set( - self, - request: product_search_service.AddProductToProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.AddProductToProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_add_product_to_product_set(self, request: product_search_service.AddProductToProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.AddProductToProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for add_product_to_product_set Override in a subclass to manipulate the request or metadata @@ -227,14 +225,7 @@ def pre_add_product_to_product_set( """ return request, metadata - def pre_create_product( - self, - request: product_search_service.CreateProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_product(self, request: product_search_service.CreateProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_product Override in a subclass to manipulate the request or metadata @@ -242,9 +233,7 @@ def pre_create_product( """ return request, metadata - def post_create_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_create_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for create_product DEPRECATED. Please use the `post_create_product_with_metadata` @@ -257,11 +246,7 @@ def post_create_product( """ return response - def post_create_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_product Override in a subclass to read or manipulate the response or metadata after it @@ -276,14 +261,7 @@ def post_create_product_with_metadata( """ return response, metadata - def pre_create_product_set( - self, - request: product_search_service.CreateProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_product_set(self, request: product_search_service.CreateProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_product_set Override in a subclass to manipulate the request or metadata @@ -291,9 +269,7 @@ def pre_create_product_set( """ return request, metadata - def post_create_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_create_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for create_product_set DEPRECATED. Please use the `post_create_product_set_with_metadata` @@ -306,13 +282,7 @@ def post_create_product_set( """ return response - def post_create_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_create_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -327,14 +297,7 @@ def post_create_product_set_with_metadata( """ return response, metadata - def pre_create_reference_image( - self, - request: product_search_service.CreateReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_reference_image(self, request: product_search_service.CreateReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_reference_image Override in a subclass to manipulate the request or metadata @@ -342,9 +305,7 @@ def pre_create_reference_image( """ return request, metadata - def post_create_reference_image( - self, response: product_search_service.ReferenceImage - ) -> product_search_service.ReferenceImage: + def post_create_reference_image(self, response: product_search_service.ReferenceImage) -> product_search_service.ReferenceImage: """Post-rpc interceptor for create_reference_image DEPRECATED. Please use the `post_create_reference_image_with_metadata` @@ -357,13 +318,7 @@ def post_create_reference_image( """ return response - def post_create_reference_image_with_metadata( - self, - response: product_search_service.ReferenceImage, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_create_reference_image_with_metadata(self, response: product_search_service.ReferenceImage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_reference_image Override in a subclass to read or manipulate the response or metadata after it @@ -378,14 +333,7 @@ def post_create_reference_image_with_metadata( """ return response, metadata - def pre_delete_product( - self, - request: product_search_service.DeleteProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_product(self, request: product_search_service.DeleteProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_product Override in a subclass to manipulate the request or metadata @@ -393,14 +341,7 @@ def pre_delete_product( """ return request, metadata - def pre_delete_product_set( - self, - request: product_search_service.DeleteProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_product_set(self, request: product_search_service.DeleteProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_product_set Override in a subclass to manipulate the request or metadata @@ -408,14 +349,7 @@ def pre_delete_product_set( """ return request, metadata - def pre_delete_reference_image( - self, - request: product_search_service.DeleteReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_reference_image(self, request: product_search_service.DeleteReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_reference_image Override in a subclass to manipulate the request or metadata @@ -423,14 +357,7 @@ def pre_delete_reference_image( """ return request, metadata - def pre_get_product( - self, - request: product_search_service.GetProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_product(self, request: product_search_service.GetProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_product Override in a subclass to manipulate the request or metadata @@ -438,9 +365,7 @@ def pre_get_product( """ return request, metadata - def post_get_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_get_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for get_product DEPRECATED. Please use the `post_get_product_with_metadata` @@ -453,11 +378,7 @@ def post_get_product( """ return response - def post_get_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_product Override in a subclass to read or manipulate the response or metadata after it @@ -472,14 +393,7 @@ def post_get_product_with_metadata( """ return response, metadata - def pre_get_product_set( - self, - request: product_search_service.GetProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_product_set(self, request: product_search_service.GetProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_product_set Override in a subclass to manipulate the request or metadata @@ -487,9 +401,7 @@ def pre_get_product_set( """ return request, metadata - def post_get_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_get_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for get_product_set DEPRECATED. Please use the `post_get_product_set_with_metadata` @@ -502,13 +414,7 @@ def post_get_product_set( """ return response - def post_get_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_get_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -523,14 +429,7 @@ def post_get_product_set_with_metadata( """ return response, metadata - def pre_get_reference_image( - self, - request: product_search_service.GetReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_reference_image(self, request: product_search_service.GetReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_reference_image Override in a subclass to manipulate the request or metadata @@ -538,9 +437,7 @@ def pre_get_reference_image( """ return request, metadata - def post_get_reference_image( - self, response: product_search_service.ReferenceImage - ) -> product_search_service.ReferenceImage: + def post_get_reference_image(self, response: product_search_service.ReferenceImage) -> product_search_service.ReferenceImage: """Post-rpc interceptor for get_reference_image DEPRECATED. Please use the `post_get_reference_image_with_metadata` @@ -553,13 +450,7 @@ def post_get_reference_image( """ return response - def post_get_reference_image_with_metadata( - self, - response: product_search_service.ReferenceImage, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_get_reference_image_with_metadata(self, response: product_search_service.ReferenceImage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_reference_image Override in a subclass to read or manipulate the response or metadata after it @@ -574,14 +465,7 @@ def post_get_reference_image_with_metadata( """ return response, metadata - def pre_import_product_sets( - self, - request: product_search_service.ImportProductSetsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ImportProductSetsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_import_product_sets(self, request: product_search_service.ImportProductSetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ImportProductSetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for import_product_sets Override in a subclass to manipulate the request or metadata @@ -589,9 +473,7 @@ def pre_import_product_sets( """ return request, metadata - def post_import_product_sets( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_import_product_sets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for import_product_sets DEPRECATED. Please use the `post_import_product_sets_with_metadata` @@ -604,11 +486,7 @@ def post_import_product_sets( """ return response - def post_import_product_sets_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_import_product_sets_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for import_product_sets Override in a subclass to read or manipulate the response or metadata after it @@ -623,14 +501,7 @@ def post_import_product_sets_with_metadata( """ return response, metadata - def pre_list_products( - self, - request: product_search_service.ListProductsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_products(self, request: product_search_service.ListProductsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_products Override in a subclass to manipulate the request or metadata @@ -638,9 +509,7 @@ def pre_list_products( """ return request, metadata - def post_list_products( - self, response: product_search_service.ListProductsResponse - ) -> product_search_service.ListProductsResponse: + def post_list_products(self, response: product_search_service.ListProductsResponse) -> product_search_service.ListProductsResponse: """Post-rpc interceptor for list_products DEPRECATED. Please use the `post_list_products_with_metadata` @@ -653,14 +522,7 @@ def post_list_products( """ return response - def post_list_products_with_metadata( - self, - response: product_search_service.ListProductsResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_products_with_metadata(self, response: product_search_service.ListProductsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_products Override in a subclass to read or manipulate the response or metadata after it @@ -675,14 +537,7 @@ def post_list_products_with_metadata( """ return response, metadata - def pre_list_product_sets( - self, - request: product_search_service.ListProductSetsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductSetsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_product_sets(self, request: product_search_service.ListProductSetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductSetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_product_sets Override in a subclass to manipulate the request or metadata @@ -690,9 +545,7 @@ def pre_list_product_sets( """ return request, metadata - def post_list_product_sets( - self, response: product_search_service.ListProductSetsResponse - ) -> product_search_service.ListProductSetsResponse: + def post_list_product_sets(self, response: product_search_service.ListProductSetsResponse) -> product_search_service.ListProductSetsResponse: """Post-rpc interceptor for list_product_sets DEPRECATED. Please use the `post_list_product_sets_with_metadata` @@ -705,14 +558,7 @@ def post_list_product_sets( """ return response - def post_list_product_sets_with_metadata( - self, - response: product_search_service.ListProductSetsResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductSetsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_product_sets_with_metadata(self, response: product_search_service.ListProductSetsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductSetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_product_sets Override in a subclass to read or manipulate the response or metadata after it @@ -727,14 +573,7 @@ def post_list_product_sets_with_metadata( """ return response, metadata - def pre_list_products_in_product_set( - self, - request: product_search_service.ListProductsInProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsInProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_products_in_product_set(self, request: product_search_service.ListProductsInProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsInProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_products_in_product_set Override in a subclass to manipulate the request or metadata @@ -742,9 +581,7 @@ def pre_list_products_in_product_set( """ return request, metadata - def post_list_products_in_product_set( - self, response: product_search_service.ListProductsInProductSetResponse - ) -> product_search_service.ListProductsInProductSetResponse: + def post_list_products_in_product_set(self, response: product_search_service.ListProductsInProductSetResponse) -> product_search_service.ListProductsInProductSetResponse: """Post-rpc interceptor for list_products_in_product_set DEPRECATED. Please use the `post_list_products_in_product_set_with_metadata` @@ -757,14 +594,7 @@ def post_list_products_in_product_set( """ return response - def post_list_products_in_product_set_with_metadata( - self, - response: product_search_service.ListProductsInProductSetResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsInProductSetResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_products_in_product_set_with_metadata(self, response: product_search_service.ListProductsInProductSetResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsInProductSetResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_products_in_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -779,14 +609,7 @@ def post_list_products_in_product_set_with_metadata( """ return response, metadata - def pre_list_reference_images( - self, - request: product_search_service.ListReferenceImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListReferenceImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_reference_images(self, request: product_search_service.ListReferenceImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListReferenceImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_reference_images Override in a subclass to manipulate the request or metadata @@ -794,9 +617,7 @@ def pre_list_reference_images( """ return request, metadata - def post_list_reference_images( - self, response: product_search_service.ListReferenceImagesResponse - ) -> product_search_service.ListReferenceImagesResponse: + def post_list_reference_images(self, response: product_search_service.ListReferenceImagesResponse) -> product_search_service.ListReferenceImagesResponse: """Post-rpc interceptor for list_reference_images DEPRECATED. Please use the `post_list_reference_images_with_metadata` @@ -809,14 +630,7 @@ def post_list_reference_images( """ return response - def post_list_reference_images_with_metadata( - self, - response: product_search_service.ListReferenceImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListReferenceImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_reference_images_with_metadata(self, response: product_search_service.ListReferenceImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListReferenceImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_reference_images Override in a subclass to read or manipulate the response or metadata after it @@ -831,14 +645,7 @@ def post_list_reference_images_with_metadata( """ return response, metadata - def pre_purge_products( - self, - request: product_search_service.PurgeProductsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.PurgeProductsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_purge_products(self, request: product_search_service.PurgeProductsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.PurgeProductsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for purge_products Override in a subclass to manipulate the request or metadata @@ -846,9 +653,7 @@ def pre_purge_products( """ return request, metadata - def post_purge_products( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_purge_products(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for purge_products DEPRECATED. Please use the `post_purge_products_with_metadata` @@ -861,11 +666,7 @@ def post_purge_products( """ return response - def post_purge_products_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_purge_products_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for purge_products Override in a subclass to read or manipulate the response or metadata after it @@ -880,14 +681,7 @@ def post_purge_products_with_metadata( """ return response, metadata - def pre_remove_product_from_product_set( - self, - request: product_search_service.RemoveProductFromProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.RemoveProductFromProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_remove_product_from_product_set(self, request: product_search_service.RemoveProductFromProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.RemoveProductFromProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for remove_product_from_product_set Override in a subclass to manipulate the request or metadata @@ -895,14 +689,7 @@ def pre_remove_product_from_product_set( """ return request, metadata - def pre_update_product( - self, - request: product_search_service.UpdateProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.UpdateProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_update_product(self, request: product_search_service.UpdateProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.UpdateProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_product Override in a subclass to manipulate the request or metadata @@ -910,9 +697,7 @@ def pre_update_product( """ return request, metadata - def post_update_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_update_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for update_product DEPRECATED. Please use the `post_update_product_with_metadata` @@ -925,11 +710,7 @@ def post_update_product( """ return response - def post_update_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_product Override in a subclass to read or manipulate the response or metadata after it @@ -944,14 +725,7 @@ def post_update_product_with_metadata( """ return response, metadata - def pre_update_product_set( - self, - request: product_search_service.UpdateProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.UpdateProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_update_product_set(self, request: product_search_service.UpdateProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.UpdateProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_product_set Override in a subclass to manipulate the request or metadata @@ -959,9 +733,7 @@ def pre_update_product_set( """ return request, metadata - def post_update_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_update_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for update_product_set DEPRECATED. Please use the `post_update_product_set_with_metadata` @@ -974,13 +746,7 @@ def post_update_product_set( """ return response - def post_update_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_update_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -996,12 +762,8 @@ def post_update_product_set_with_metadata( return response, metadata def pre_get_operation( - self, - request: operations_pb2.GetOperationRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -1034,20 +796,21 @@ class ProductSearchRestTransport(_BaseProductSearchRestTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to - put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -1056,21 +819,20 @@ class ProductSearchRestTransport(_BaseProductSearchRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ProductSearchRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ProductSearchRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -1114,11 +876,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -1135,46 +896,40 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # 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.GetOperation": [ + 'google.longrunning.Operations.GetOperation': [ { - "method": "get", - "uri": "/v1/{name=projects/*/operations/*}", + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', }, { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', }, { - "method": "get", - "uri": "/v1/{name=operations/*}", + 'method': 'get', + 'uri': '/v1/{name=operations/*}', }, { - "method": "get", - "uri": "/v1/{name=locations/*/operations/*}", + 'method': 'get', + 'uri': '/v1/{name=locations/*/operations/*}', }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AddProductToProductSet( - _BaseProductSearchRestTransport._BaseAddProductToProductSet, - ProductSearchRestStub, - ): + class _AddProductToProductSet(_BaseProductSearchRestTransport._BaseAddProductToProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.AddProductToProductSet") @@ -1186,85 +941,69 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.AddProductToProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.AddProductToProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the add product to product - set method over HTTP. - - Args: - request (~.product_search_service.AddProductToProductSetRequest): - The request object. Request message for the ``AddProductToProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + set method over HTTP. + + Args: + request (~.product_search_service.AddProductToProductSetRequest): + The request object. Request message for the ``AddProductToProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_http_options() - request, metadata = self._interceptor.pre_add_product_to_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_add_product_to_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.AddProductToProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "AddProductToProductSet", "httpRequest": http_request, @@ -1273,24 +1012,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._AddProductToProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._AddProductToProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _CreateProduct( - _BaseProductSearchRestTransport._BaseCreateProduct, ProductSearchRestStub - ): + class _CreateProduct(_BaseProductSearchRestTransport._BaseCreateProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateProduct") @@ -1302,29 +1031,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.CreateProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the create product method over HTTP. Args: @@ -1343,44 +1070,32 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateProduct._get_http_options() request, metadata = self._interceptor.pre_create_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateProduct._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateProduct._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateProduct._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.CreateProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "CreateProduct", "httpRequest": http_request, @@ -1389,15 +1104,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1412,24 +1119,20 @@ def __call__( resp = self._interceptor.post_create_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.create_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "CreateProduct", "metadata": http_response["headers"], @@ -1438,9 +1141,7 @@ def __call__( ) return resp - class _CreateProductSet( - _BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub - ): + class _CreateProductSet(_BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateProductSet") @@ -1452,29 +1153,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.CreateProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the create product set method over HTTP. Args: @@ -1498,46 +1197,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateProductSet._get_http_options() - request, metadata = self._interceptor.pre_create_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.CreateProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "CreateProductSet", "httpRequest": http_request, @@ -1546,15 +1231,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1569,26 +1246,20 @@ def __call__( resp = self._interceptor.post_create_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.create_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "CreateProductSet", "metadata": http_response["headers"], @@ -1597,9 +1268,7 @@ def __call__( ) return resp - class _CreateReferenceImage( - _BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub - ): + class _CreateReferenceImage(_BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateReferenceImage") @@ -1611,29 +1280,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def __call__(self, + request: product_search_service.CreateReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ReferenceImage: r"""Call the create reference image method over HTTP. Args: @@ -1654,46 +1321,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_create_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.CreateReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "CreateReferenceImage", "httpRequest": http_request, @@ -1702,15 +1355,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1725,26 +1370,20 @@ def __call__( resp = self._interceptor.post_create_reference_image(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_reference_image_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_reference_image_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ReferenceImage.to_json( - response - ) + response_payload = product_search_service.ReferenceImage.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.create_reference_image", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "CreateReferenceImage", "metadata": http_response["headers"], @@ -1753,9 +1392,7 @@ def __call__( ) return resp - class _DeleteProduct( - _BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub - ): + class _DeleteProduct(_BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProduct") @@ -1767,28 +1404,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete product method over HTTP. Args: @@ -1803,40 +1438,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteProduct._get_http_options() request, metadata = self._interceptor.pre_delete_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProduct._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.DeleteProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "DeleteProduct", "httpRequest": http_request, @@ -1845,23 +1470,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteProductSet( - _BaseProductSearchRestTransport._BaseDeleteProductSet, ProductSearchRestStub - ): + class _DeleteProductSet(_BaseProductSearchRestTransport._BaseDeleteProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProductSet") @@ -1873,28 +1489,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete product set method over HTTP. Args: @@ -1909,42 +1523,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_http_options() - request, metadata = self._interceptor.pre_delete_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_delete_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.DeleteProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "DeleteProductSet", "httpRequest": http_request, @@ -1953,23 +1555,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteReferenceImage( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage, ProductSearchRestStub - ): + class _DeleteReferenceImage(_BaseProductSearchRestTransport._BaseDeleteReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteReferenceImage") @@ -1981,28 +1574,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete reference image method over HTTP. Args: @@ -2017,42 +1608,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_delete_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_delete_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.DeleteReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "DeleteReferenceImage", "httpRequest": http_request, @@ -2061,23 +1640,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetProduct( - _BaseProductSearchRestTransport._BaseGetProduct, ProductSearchRestStub - ): + class _GetProduct(_BaseProductSearchRestTransport._BaseGetProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetProduct") @@ -2089,28 +1659,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.GetProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the get product method over HTTP. Args: @@ -2129,44 +1697,30 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetProduct._get_http_options() request, metadata = self._interceptor.pre_get_product(request, metadata) - transcoded_request = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_transcoded_request( - http_options, request - ) - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetProduct._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_query_params_json( - transcoded_request - ) - ) + query_params = _BaseProductSearchRestTransport._BaseGetProduct._get_query_params_json(transcoded_request) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.GetProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetProduct", "httpRequest": http_request, @@ -2175,14 +1729,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2197,24 +1744,20 @@ def __call__( resp = self._interceptor.post_get_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.get_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetProduct", "metadata": http_response["headers"], @@ -2223,9 +1766,7 @@ def __call__( ) return resp - class _GetProductSet( - _BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub - ): + class _GetProductSet(_BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetProductSet") @@ -2237,28 +1778,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.GetProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the get product set method over HTTP. Args: @@ -2282,40 +1821,30 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetProductSet._get_http_options() request, metadata = self._interceptor.pre_get_product_set(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseGetProductSet._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.GetProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetProductSet", "httpRequest": http_request, @@ -2324,14 +1853,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2346,26 +1868,20 @@ def __call__( resp = self._interceptor.post_get_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.get_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetProductSet", "metadata": http_response["headers"], @@ -2374,9 +1890,7 @@ def __call__( ) return resp - class _GetReferenceImage( - _BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub - ): + class _GetReferenceImage(_BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetReferenceImage") @@ -2388,28 +1902,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def __call__(self, + request: product_search_service.GetReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ReferenceImage: r"""Call the get reference image method over HTTP. Args: @@ -2430,42 +1942,30 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_get_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_get_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.GetReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetReferenceImage", "httpRequest": http_request, @@ -2474,14 +1974,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2496,26 +1989,20 @@ def __call__( resp = self._interceptor.post_get_reference_image(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_reference_image_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_reference_image_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ReferenceImage.to_json( - response - ) + response_payload = product_search_service.ReferenceImage.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.get_reference_image", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetReferenceImage", "metadata": http_response["headers"], @@ -2524,9 +2011,7 @@ def __call__( ) return resp - class _ImportProductSets( - _BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub - ): + class _ImportProductSets(_BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ImportProductSets") @@ -2538,29 +2023,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.ImportProductSetsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: product_search_service.ImportProductSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the import product sets method over HTTP. Args: @@ -2582,46 +2065,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseImportProductSets._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseImportProductSets._get_http_options() - request, metadata = self._interceptor.pre_import_product_sets( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseImportProductSets._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_import_product_sets(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseImportProductSets._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseImportProductSets._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseImportProductSets._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseImportProductSets._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseImportProductSets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.ImportProductSets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ImportProductSets", "httpRequest": http_request, @@ -2630,15 +2099,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ImportProductSets._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._ImportProductSets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2651,24 +2112,20 @@ def __call__( resp = self._interceptor.post_import_product_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_import_product_sets_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_import_product_sets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.import_product_sets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ImportProductSets", "metadata": http_response["headers"], @@ -2677,9 +2134,7 @@ def __call__( ) return resp - class _ListProducts( - _BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub - ): + class _ListProducts(_BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProducts") @@ -2691,28 +2146,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductsResponse: + def __call__(self, + request: product_search_service.ListProductsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductsResponse: r"""Call the list products method over HTTP. Args: @@ -2731,40 +2184,30 @@ def __call__( Response message for the ``ListProducts`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProducts._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProducts._get_http_options() request, metadata = self._interceptor.pre_list_products(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseListProducts._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseListProducts._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProducts._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProducts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.ListProducts", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListProducts", "httpRequest": http_request, @@ -2773,14 +2216,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListProducts._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2795,26 +2231,20 @@ def __call__( resp = self._interceptor.post_list_products(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_products_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_products_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductsResponse.to_json(response) - ) + response_payload = product_search_service.ListProductsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.list_products", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListProducts", "metadata": http_response["headers"], @@ -2823,9 +2253,7 @@ def __call__( ) return resp - class _ListProductSets( - _BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub - ): + class _ListProductSets(_BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProductSets") @@ -2837,28 +2265,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductSetsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductSetsResponse: + def __call__(self, + request: product_search_service.ListProductSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductSetsResponse: r"""Call the list product sets method over HTTP. Args: @@ -2877,42 +2303,30 @@ def __call__( Response message for the ``ListProductSets`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProductSets._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProductSets._get_http_options() - request, metadata = self._interceptor.pre_list_product_sets( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListProductSets._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_product_sets(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListProductSets._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProductSets._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProductSets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.ListProductSets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListProductSets", "httpRequest": http_request, @@ -2921,14 +2335,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListProductSets._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListProductSets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2943,26 +2350,20 @@ def __call__( resp = self._interceptor.post_list_product_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_product_sets_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_product_sets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductSetsResponse.to_json(response) - ) + response_payload = product_search_service.ListProductSetsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.list_product_sets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListProductSets", "metadata": http_response["headers"], @@ -2971,10 +2372,7 @@ def __call__( ) return resp - class _ListProductsInProductSet( - _BaseProductSearchRestTransport._BaseListProductsInProductSet, - ProductSearchRestStub, - ): + class _ListProductsInProductSet(_BaseProductSearchRestTransport._BaseListProductsInProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProductsInProductSet") @@ -2986,86 +2384,72 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductsInProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductsInProductSetResponse: + def __call__(self, + request: product_search_service.ListProductsInProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductsInProductSetResponse: r"""Call the list products in product - set method over HTTP. - - Args: - request (~.product_search_service.ListProductsInProductSetRequest): - The request object. Request message for the ``ListProductsInProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.product_search_service.ListProductsInProductSetResponse: - Response message for the ``ListProductsInProductSet`` - method. + set method over HTTP. + + Args: + request (~.product_search_service.ListProductsInProductSetRequest): + The request object. Request message for the ``ListProductsInProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.product_search_service.ListProductsInProductSetResponse: + Response message for the ``ListProductsInProductSet`` + method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_http_options() - request, metadata = self._interceptor.pre_list_products_in_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_products_in_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.ListProductsInProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListProductsInProductSet", "httpRequest": http_request, @@ -3074,16 +2458,7 @@ def __call__( ) # Send the request - response = ( - ProductSearchRestTransport._ListProductsInProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - ) + response = ProductSearchRestTransport._ListProductsInProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3098,28 +2473,20 @@ def __call__( resp = self._interceptor.post_list_products_in_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_products_in_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_products_in_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductsInProductSetResponse.to_json( - response - ) - ) + response_payload = product_search_service.ListProductsInProductSetResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.list_products_in_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListProductsInProductSet", "metadata": http_response["headers"], @@ -3128,9 +2495,7 @@ def __call__( ) return resp - class _ListReferenceImages( - _BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub - ): + class _ListReferenceImages(_BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListReferenceImages") @@ -3142,28 +2507,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListReferenceImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListReferenceImagesResponse: + def __call__(self, + request: product_search_service.ListReferenceImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListReferenceImagesResponse: r"""Call the list reference images method over HTTP. Args: @@ -3182,42 +2545,30 @@ def __call__( Response message for the ``ListReferenceImages`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListReferenceImages._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListReferenceImages._get_http_options() - request, metadata = self._interceptor.pre_list_reference_images( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListReferenceImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_reference_images(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListReferenceImages._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListReferenceImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListReferenceImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.ListReferenceImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListReferenceImages", "httpRequest": http_request, @@ -3226,14 +2577,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListReferenceImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListReferenceImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3248,28 +2592,20 @@ def __call__( resp = self._interceptor.post_list_reference_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_reference_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_reference_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListReferenceImagesResponse.to_json( - response - ) - ) + response_payload = product_search_service.ListReferenceImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.list_reference_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "ListReferenceImages", "metadata": http_response["headers"], @@ -3278,9 +2614,7 @@ def __call__( ) return resp - class _PurgeProducts( - _BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub - ): + class _PurgeProducts(_BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.PurgeProducts") @@ -3292,29 +2626,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.PurgeProductsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: product_search_service.PurgeProductsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the purge products method over HTTP. Args: @@ -3336,44 +2668,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BasePurgeProducts._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BasePurgeProducts._get_http_options() request, metadata = self._interceptor.pre_purge_products(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BasePurgeProducts._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BasePurgeProducts._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BasePurgeProducts._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BasePurgeProducts._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BasePurgeProducts._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BasePurgeProducts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.PurgeProducts", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "PurgeProducts", "httpRequest": http_request, @@ -3382,15 +2702,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._PurgeProducts._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._PurgeProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3403,24 +2715,20 @@ def __call__( resp = self._interceptor.post_purge_products(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_purge_products_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_purge_products_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.purge_products", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "PurgeProducts", "metadata": http_response["headers"], @@ -3429,10 +2737,7 @@ def __call__( ) return resp - class _RemoveProductFromProductSet( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, - ProductSearchRestStub, - ): + class _RemoveProductFromProductSet(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.RemoveProductFromProductSet") @@ -3444,85 +2749,69 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.RemoveProductFromProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.RemoveProductFromProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the remove product from - product set method over HTTP. - - Args: - request (~.product_search_service.RemoveProductFromProductSetRequest): - The request object. Request message for the ``RemoveProductFromProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + product set method over HTTP. + + Args: + request (~.product_search_service.RemoveProductFromProductSetRequest): + The request object. Request message for the ``RemoveProductFromProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_http_options() - request, metadata = self._interceptor.pre_remove_product_from_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_remove_product_from_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.RemoveProductFromProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "RemoveProductFromProductSet", "httpRequest": http_request, @@ -3531,26 +2820,14 @@ def __call__( ) # Send the request - response = ( - ProductSearchRestTransport._RemoveProductFromProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ProductSearchRestTransport._RemoveProductFromProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _UpdateProduct( - _BaseProductSearchRestTransport._BaseUpdateProduct, ProductSearchRestStub - ): + class _UpdateProduct(_BaseProductSearchRestTransport._BaseUpdateProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProduct") @@ -3562,29 +2839,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.UpdateProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.UpdateProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the update product method over HTTP. Args: @@ -3603,44 +2878,32 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseUpdateProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseUpdateProduct._get_http_options() request, metadata = self._interceptor.pre_update_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProduct._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseUpdateProduct._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseUpdateProduct._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseUpdateProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseUpdateProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.UpdateProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "UpdateProduct", "httpRequest": http_request, @@ -3649,15 +2912,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._UpdateProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._UpdateProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3672,24 +2927,20 @@ def __call__( resp = self._interceptor.post_update_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_update_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.update_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "UpdateProduct", "metadata": http_response["headers"], @@ -3698,9 +2949,7 @@ def __call__( ) return resp - class _UpdateProductSet( - _BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub - ): + class _UpdateProductSet(_BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProductSet") @@ -3712,29 +2961,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.UpdateProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.UpdateProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the update product set method over HTTP. Args: @@ -3758,46 +3005,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseUpdateProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_http_options() - request, metadata = self._interceptor.pre_update_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.UpdateProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "UpdateProductSet", "httpRequest": http_request, @@ -3806,15 +3039,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._UpdateProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._UpdateProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3829,26 +3054,20 @@ def __call__( resp = self._interceptor.post_update_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_update_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchClient.update_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "UpdateProductSet", "metadata": http_response["headers"], @@ -3858,206 +3077,162 @@ def __call__( return resp @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], empty_pb2.Empty - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AddProductToProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._AddProductToProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], product_search_service.Product - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + product_search_service.Product]: # 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._CreateProduct(self._session, self._host, self._interceptor) # type: ignore + return self._CreateProduct(self._session, self._host, self._interceptor) # type: ignore @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - product_search_service.ProductSet, - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet]: # 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._CreateProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._CreateProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage]: # 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._CreateReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._CreateReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def delete_product( - self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteProduct(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteProduct(self._session, self._host, self._interceptor) # type: ignore @property - def delete_product_set( - self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], product_search_service.Product - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + product_search_service.Product]: # 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._GetProduct(self._session, self._host, self._interceptor) # type: ignore + return self._GetProduct(self._session, self._host, self._interceptor) # type: ignore @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], product_search_service.ProductSet - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + product_search_service.ProductSet]: # 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._GetProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._GetProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage]: # 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._GetReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._GetReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations_pb2.Operation - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + 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._ImportProductSets(self._session, self._host, self._interceptor) # type: ignore + return self._ImportProductSets(self._session, self._host, self._interceptor) # type: ignore @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - product_search_service.ListProductsResponse, - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse]: # 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._ListProducts(self._session, self._host, self._interceptor) # type: ignore + return self._ListProducts(self._session, self._host, self._interceptor) # type: ignore @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - product_search_service.ListProductSetsResponse, - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse]: # 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._ListProductSets(self._session, self._host, self._interceptor) # type: ignore + return self._ListProductSets(self._session, self._host, self._interceptor) # type: ignore @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - product_search_service.ListProductsInProductSetResponse, - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse]: # 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._ListProductsInProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._ListProductsInProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - product_search_service.ListReferenceImagesResponse, - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse]: # 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._ListReferenceImages(self._session, self._host, self._interceptor) # type: ignore + return self._ListReferenceImages(self._session, self._host, self._interceptor) # type: ignore @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], operations_pb2.Operation - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + 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._PurgeProducts(self._session, self._host, self._interceptor) # type: ignore + return self._PurgeProducts(self._session, self._host, self._interceptor) # type: ignore @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._RemoveProductFromProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._RemoveProductFromProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], product_search_service.Product - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + product_search_service.Product]: # 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._UpdateProduct(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateProduct(self._session, self._host, self._interceptor) # type: ignore @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - product_search_service.ProductSet, - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet]: # 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._UpdateProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateProductSet(self._session, self._host, self._interceptor) # type: ignore @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation( - _BaseProductSearchRestTransport._BaseGetOperation, ProductSearchRestStub - ): + class _GetOperation(_BaseProductSearchRestTransport._BaseGetOperation, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetOperation") @@ -4069,28 +3244,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: operations_pb2.GetOperationRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. Args: @@ -4108,40 +3282,30 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetOperation._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetOperation._get_http_options() request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseGetOperation._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetOperation._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1.ProductSearchClient.GetOperation", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetOperation", "httpRequest": http_request, @@ -4150,14 +3314,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetOperation._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4168,21 +3325,19 @@ def __call__( resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1.ProductSearchAsyncClient.GetOperation", - extra={ + extra = { "serviceName": "google.cloud.vision.v1.ProductSearch", "rpcName": "GetOperation", "httpResponse": http_response, @@ -4199,4 +3354,6 @@ def close(self): self._session.close() -__all__ = ("ProductSearchRestTransport",) +__all__=( + 'ProductSearchRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest_base.py index e704231eadf4..9a86ad652029 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/transports/rest_base.py @@ -14,17 +14,19 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore class _BaseProductSearchRestTransport(ProductSearchTransport): @@ -40,16 +42,14 @@ class _BaseProductSearchRestTransport(ProductSearchTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -73,9 +73,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -86,39 +84,33 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAddProductToProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/productSets/*}:addProduct", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/productSets/*}:addProduct', + 'body': '*', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.AddProductToProductSetRequest.pb( - request - ) + pb_request = product_search_service.AddProductToProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -127,23 +119,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseAddProductToProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -152,24 +138,20 @@ class _BaseCreateProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/products", - "body": "product", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/products', + 'body': 'product', + }, ] return http_options @@ -184,23 +166,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -209,24 +185,20 @@ class _BaseCreateProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/productSets", - "body": "product_set", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/productSets', + 'body': 'product_set', + }, ] return http_options @@ -241,23 +213,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -266,24 +232,20 @@ class _BaseCreateReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*/products/*}/referenceImages", - "body": "reference_image", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/products/*}/referenceImages', + 'body': 'reference_image', + }, ] return http_options @@ -298,23 +260,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -323,23 +279,19 @@ class _BaseDeleteProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/products/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/products/*}', + }, ] return http_options @@ -351,17 +303,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -370,23 +316,19 @@ class _BaseDeleteProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/productSets/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/productSets/*}', + }, ] return http_options @@ -398,17 +340,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -417,23 +353,19 @@ class _BaseDeleteReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/products/*/referenceImages/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/products/*/referenceImages/*}', + }, ] return http_options @@ -445,17 +377,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -464,23 +390,19 @@ class _BaseGetProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/products/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/products/*}', + }, ] return http_options @@ -492,17 +414,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -511,23 +427,19 @@ class _BaseGetProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/productSets/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/productSets/*}', + }, ] return http_options @@ -539,17 +451,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -558,23 +464,19 @@ class _BaseGetReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/products/*/referenceImages/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/products/*/referenceImages/*}', + }, ] return http_options @@ -586,17 +488,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -605,24 +501,20 @@ class _BaseImportProductSets: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/productSets:import", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/productSets:import', + 'body': '*', + }, ] return http_options @@ -637,23 +529,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseImportProductSets._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseImportProductSets._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -662,23 +548,19 @@ class _BaseListProducts: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/products", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/products', + }, ] return http_options @@ -690,17 +572,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProducts._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProducts._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -709,23 +585,19 @@ class _BaseListProductSets: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/productSets", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/productSets', + }, ] return http_options @@ -737,17 +609,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProductSets._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProductSets._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -756,47 +622,35 @@ class _BaseListProductsInProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/productSets/*}/products", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/productSets/*}/products', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.ListProductsInProductSetRequest.pb( - request - ) + pb_request = product_search_service.ListProductsInProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProductsInProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -805,23 +659,19 @@ class _BaseListReferenceImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/products/*}/referenceImages", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/products/*}/referenceImages', + }, ] return http_options @@ -833,17 +683,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListReferenceImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListReferenceImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -852,24 +696,20 @@ class _BasePurgeProducts: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/products:purge", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/products:purge', + 'body': '*', + }, ] return http_options @@ -884,23 +724,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BasePurgeProducts._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BasePurgeProducts._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -909,32 +743,26 @@ class _BaseRemoveProductFromProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/productSets/*}:removeProduct", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/productSets/*}:removeProduct', + 'body': '*', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.RemoveProductFromProductSetRequest.pb( - request - ) + pb_request = product_search_service.RemoveProductFromProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -943,23 +771,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -968,24 +790,20 @@ class _BaseUpdateProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{product.name=projects/*/locations/*/products/*}", - "body": "product", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{product.name=projects/*/locations/*/products/*}', + 'body': 'product', + }, ] return http_options @@ -1000,23 +818,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseUpdateProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseUpdateProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -1025,24 +837,20 @@ class _BaseUpdateProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{product_set.name=projects/*/locations/*/productSets/*}", - "body": "product_set", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{product_set.name=projects/*/locations/*/productSets/*}', + 'body': 'product_set', + }, ] return http_options @@ -1057,23 +865,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseUpdateProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseUpdateProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -1084,36 +886,38 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=locations/*/operations/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=locations/*/operations/*}', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = json.loads(json.dumps(transcoded_request['query_params'])) return query_params -__all__ = ("_BaseProductSearchRestTransport",) +__all__=( + '_BaseProductSearchRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/__init__.py index 6d3af4c629f5..2b5430e8fc17 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/__init__.py @@ -13,7 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .geometry import BoundingPoly, NormalizedVertex, Position, Vertex +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Position, + Vertex, +) from .image_annotator import ( AnnotateFileRequest, AnnotateFileResponse, @@ -46,7 +51,6 @@ ImageSource, InputConfig, LatLongRect, - Likelihood, LocalizedObjectAnnotation, LocationInfo, OperationMetadata, @@ -55,8 +59,12 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, + Likelihood, +) +from .product_search import ( + ProductSearchParams, + ProductSearchResults, ) -from .product_search import ProductSearchParams, ProductSearchResults from .product_search_service import ( AddProductToProductSetRequest, BatchOperationMetadata, @@ -90,92 +98,101 @@ UpdateProductRequest, UpdateProductSetRequest, ) -from .text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word -from .web_detection import WebDetection +from .text_annotation import ( + Block, + Page, + Paragraph, + Symbol, + TextAnnotation, + Word, +) +from .web_detection import ( + WebDetection, +) __all__ = ( - "BoundingPoly", - "NormalizedVertex", - "Position", - "Vertex", - "AnnotateFileRequest", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "Image", - "ImageAnnotationContext", - "ImageContext", - "ImageProperties", - "ImageSource", - "InputConfig", - "LatLongRect", - "LocalizedObjectAnnotation", - "LocationInfo", - "OperationMetadata", - "OutputConfig", - "Property", - "SafeSearchAnnotation", - "TextDetectionParams", - "WebDetectionParams", - "Likelihood", - "ProductSearchParams", - "ProductSearchResults", - "AddProductToProductSetRequest", - "BatchOperationMetadata", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "Product", - "ProductSet", - "ProductSetPurgeConfig", - "PurgeProductsRequest", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Block", - "Page", - "Paragraph", - "Symbol", - "TextAnnotation", - "Word", - "WebDetection", + 'BoundingPoly', + 'NormalizedVertex', + 'Position', + 'Vertex', + 'AnnotateFileRequest', + 'AnnotateFileResponse', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'AsyncBatchAnnotateImagesRequest', + 'AsyncBatchAnnotateImagesResponse', + 'BatchAnnotateFilesRequest', + 'BatchAnnotateFilesResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'ColorInfo', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'DominantColorsAnnotation', + 'EntityAnnotation', + 'FaceAnnotation', + 'Feature', + 'GcsDestination', + 'GcsSource', + 'Image', + 'ImageAnnotationContext', + 'ImageContext', + 'ImageProperties', + 'ImageSource', + 'InputConfig', + 'LatLongRect', + 'LocalizedObjectAnnotation', + 'LocationInfo', + 'OperationMetadata', + 'OutputConfig', + 'Property', + 'SafeSearchAnnotation', + 'TextDetectionParams', + 'WebDetectionParams', + 'Likelihood', + 'ProductSearchParams', + 'ProductSearchResults', + 'AddProductToProductSetRequest', + 'BatchOperationMetadata', + 'CreateProductRequest', + 'CreateProductSetRequest', + 'CreateReferenceImageRequest', + 'DeleteProductRequest', + 'DeleteProductSetRequest', + 'DeleteReferenceImageRequest', + 'GetProductRequest', + 'GetProductSetRequest', + 'GetReferenceImageRequest', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ListProductsRequest', + 'ListProductsResponse', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'Product', + 'ProductSet', + 'ProductSetPurgeConfig', + 'PurgeProductsRequest', + 'ReferenceImage', + 'RemoveProductFromProductSetRequest', + 'UpdateProductRequest', + 'UpdateProductSetRequest', + 'Block', + 'Page', + 'Paragraph', + 'Symbol', + 'TextAnnotation', + 'Word', + 'WebDetection', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/geometry.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/geometry.py index 2980098d1d67..f848fc78244f 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/geometry.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/geometry.py @@ -19,13 +19,14 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1", + package='google.cloud.vision.v1', manifest={ - "Vertex", - "NormalizedVertex", - "BoundingPoly", - "Position", + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + 'Position', }, ) @@ -84,15 +85,15 @@ class BoundingPoly(proto.Message): The bounding polygon normalized vertices. """ - vertices: MutableSequence["Vertex"] = proto.RepeatedField( + vertices: MutableSequence['Vertex'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Vertex", + message='Vertex', ) - normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="NormalizedVertex", + message='NormalizedVertex', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/image_annotator.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/image_annotator.py index 524c4df5c0c9..71c9882cd43b 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/image_annotator.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/image_annotator.py @@ -17,58 +17,61 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search +from google.cloud.vision_v1.types import text_annotation +from google.cloud.vision_v1.types import web_detection as gcv_web_detection from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.type import color_pb2 # type: ignore from google.type import latlng_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1.types import geometry, product_search, text_annotation -from google.cloud.vision_v1.types import web_detection as gcv_web_detection __protobuf__ = proto.module( - package="google.cloud.vision.v1", + package='google.cloud.vision.v1', manifest={ - "Likelihood", - "Feature", - "ImageSource", - "Image", - "FaceAnnotation", - "LocationInfo", - "Property", - "EntityAnnotation", - "LocalizedObjectAnnotation", - "SafeSearchAnnotation", - "LatLongRect", - "ColorInfo", - "DominantColorsAnnotation", - "ImageProperties", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "WebDetectionParams", - "TextDetectionParams", - "ImageContext", - "AnnotateImageRequest", - "ImageAnnotationContext", - "AnnotateImageResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "AnnotateFileRequest", - "AnnotateFileResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "InputConfig", - "OutputConfig", - "GcsSource", - "GcsDestination", - "OperationMetadata", + 'Likelihood', + 'Feature', + 'ImageSource', + 'Image', + 'FaceAnnotation', + 'LocationInfo', + 'Property', + 'EntityAnnotation', + 'LocalizedObjectAnnotation', + 'SafeSearchAnnotation', + 'LatLongRect', + 'ColorInfo', + 'DominantColorsAnnotation', + 'ImageProperties', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'WebDetectionParams', + 'TextDetectionParams', + 'ImageContext', + 'AnnotateImageRequest', + 'ImageAnnotationContext', + 'AnnotateImageResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'AnnotateFileRequest', + 'AnnotateFileResponse', + 'BatchAnnotateFilesRequest', + 'BatchAnnotateFilesResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateImagesRequest', + 'AsyncBatchAnnotateImagesResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + 'OperationMetadata', }, ) @@ -118,7 +121,6 @@ class Feature(proto.Message): ``TEXT_DETECTION`` also support "builtin/weekly" for the bleeding edge release updated weekly. """ - class Type(proto.Enum): r"""Type of Google Cloud Vision API feature to be extracted. @@ -254,10 +256,10 @@ class Image(proto.Message): proto.BYTES, number=1, ) - source: "ImageSource" = proto.Field( + source: 'ImageSource' = proto.Field( proto.MESSAGE, number=2, - message="ImageSource", + message='ImageSource', ) @@ -326,7 +328,6 @@ class Landmark(proto.Message): position (google.cloud.vision_v1.types.Position): Face landmark position. """ - class Type(proto.Enum): r"""Face landmark (feature) type. Left and right are defined from the vantage of the viewer of the image without considering mirror @@ -448,10 +449,10 @@ class Type(proto.Enum): LEFT_CHEEK_CENTER = 35 RIGHT_CHEEK_CENTER = 36 - type_: "FaceAnnotation.Landmark.Type" = proto.Field( + type_: 'FaceAnnotation.Landmark.Type' = proto.Field( proto.ENUM, number=3, - enum="FaceAnnotation.Landmark.Type", + enum='FaceAnnotation.Landmark.Type', ) position: geometry.Position = proto.Field( proto.MESSAGE, @@ -494,40 +495,40 @@ class Type(proto.Enum): proto.FLOAT, number=8, ) - joy_likelihood: "Likelihood" = proto.Field( + joy_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) - sorrow_likelihood: "Likelihood" = proto.Field( + sorrow_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=10, - enum="Likelihood", + enum='Likelihood', ) - anger_likelihood: "Likelihood" = proto.Field( + anger_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=11, - enum="Likelihood", + enum='Likelihood', ) - surprise_likelihood: "Likelihood" = proto.Field( + surprise_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=12, - enum="Likelihood", + enum='Likelihood', ) - under_exposed_likelihood: "Likelihood" = proto.Field( + under_exposed_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=13, - enum="Likelihood", + enum='Likelihood', ) - blurred_likelihood: "Likelihood" = proto.Field( + blurred_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=14, - enum="Likelihood", + enum='Likelihood', ) - headwear_likelihood: "Likelihood" = proto.Field( + headwear_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=15, - enum="Likelihood", + enum='Likelihood', ) @@ -646,15 +647,15 @@ class EntityAnnotation(proto.Message): number=7, message=geometry.BoundingPoly, ) - locations: MutableSequence["LocationInfo"] = proto.RepeatedField( + locations: MutableSequence['LocationInfo'] = proto.RepeatedField( proto.MESSAGE, number=8, - message="LocationInfo", + message='LocationInfo', ) - properties: MutableSequence["Property"] = proto.RepeatedField( + properties: MutableSequence['Property'] = proto.RepeatedField( proto.MESSAGE, number=9, - message="Property", + message='Property', ) @@ -732,30 +733,30 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult: "Likelihood" = proto.Field( + adult: 'Likelihood' = proto.Field( proto.ENUM, number=1, - enum="Likelihood", + enum='Likelihood', ) - spoof: "Likelihood" = proto.Field( + spoof: 'Likelihood' = proto.Field( proto.ENUM, number=2, - enum="Likelihood", + enum='Likelihood', ) - medical: "Likelihood" = proto.Field( + medical: 'Likelihood' = proto.Field( proto.ENUM, number=3, - enum="Likelihood", + enum='Likelihood', ) - violence: "Likelihood" = proto.Field( + violence: 'Likelihood' = proto.Field( proto.ENUM, number=4, - enum="Likelihood", + enum='Likelihood', ) - racy: "Likelihood" = proto.Field( + racy: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) @@ -819,10 +820,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence["ColorInfo"] = proto.RepeatedField( + colors: MutableSequence['ColorInfo'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ColorInfo", + message='ColorInfo', ) @@ -835,10 +836,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: "DominantColorsAnnotation" = proto.Field( + dominant_colors: 'DominantColorsAnnotation' = proto.Field( proto.MESSAGE, number=1, - message="DominantColorsAnnotation", + message='DominantColorsAnnotation', ) @@ -882,10 +883,10 @@ class CropHintsAnnotation(proto.Message): Crop hint results. """ - crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( + crop_hints: MutableSequence['CropHint'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="CropHint", + message='CropHint', ) @@ -937,11 +938,11 @@ class TextDetectionParams(proto.Message): A list of advanced OCR options to further fine-tune OCR behavior. Current valid values are: - - ``legacy_layout``: a heuristics layout detection - algorithm, which serves as an alternative to the current - ML-based layout detection algorithm. Customers can choose - the best suitable layout algorithm based on their - situation. + - ``legacy_layout``: a heuristics layout detection + algorithm, which serves as an alternative to the current + ML-based layout detection algorithm. Customers can choose + the best suitable layout algorithm based on their + situation. """ enable_text_detection_confidence_score: bool = proto.Field( @@ -982,34 +983,34 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect: "LatLongRect" = proto.Field( + lat_long_rect: 'LatLongRect' = proto.Field( proto.MESSAGE, number=1, - message="LatLongRect", + message='LatLongRect', ) language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params: "CropHintsParams" = proto.Field( + crop_hints_params: 'CropHintsParams' = proto.Field( proto.MESSAGE, number=4, - message="CropHintsParams", + message='CropHintsParams', ) product_search_params: product_search.ProductSearchParams = proto.Field( proto.MESSAGE, number=5, message=product_search.ProductSearchParams, ) - web_detection_params: "WebDetectionParams" = proto.Field( + web_detection_params: 'WebDetectionParams' = proto.Field( proto.MESSAGE, number=6, - message="WebDetectionParams", + message='WebDetectionParams', ) - text_detection_params: "TextDetectionParams" = proto.Field( + text_detection_params: 'TextDetectionParams' = proto.Field( proto.MESSAGE, number=12, - message="TextDetectionParams", + message='TextDetectionParams', ) @@ -1028,20 +1029,20 @@ class AnnotateImageRequest(proto.Message): image. """ - image: "Image" = proto.Field( + image: 'Image' = proto.Field( proto.MESSAGE, number=1, - message="Image", + message='Image', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) @@ -1121,57 +1122,55 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( + face_annotations: MutableSequence['FaceAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="FaceAnnotation", + message='FaceAnnotation', ) - landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + landmark_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="EntityAnnotation", + message='EntityAnnotation', ) - logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + logo_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="EntityAnnotation", + message='EntityAnnotation', ) - label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + label_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="EntityAnnotation", + message='EntityAnnotation', ) - localized_object_annotations: MutableSequence[ - "LocalizedObjectAnnotation" - ] = proto.RepeatedField( + localized_object_annotations: MutableSequence['LocalizedObjectAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=22, - message="LocalizedObjectAnnotation", + message='LocalizedObjectAnnotation', ) - text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + text_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="EntityAnnotation", + message='EntityAnnotation', ) full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation: "SafeSearchAnnotation" = proto.Field( + safe_search_annotation: 'SafeSearchAnnotation' = proto.Field( proto.MESSAGE, number=6, - message="SafeSearchAnnotation", + message='SafeSearchAnnotation', ) - image_properties_annotation: "ImageProperties" = proto.Field( + image_properties_annotation: 'ImageProperties' = proto.Field( proto.MESSAGE, number=8, - message="ImageProperties", + message='ImageProperties', ) - crop_hints_annotation: "CropHintsAnnotation" = proto.Field( + crop_hints_annotation: 'CropHintsAnnotation' = proto.Field( proto.MESSAGE, number=11, - message="CropHintsAnnotation", + message='CropHintsAnnotation', ) web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, @@ -1188,10 +1187,10 @@ class AnnotateImageResponse(proto.Message): number=9, message=status_pb2.Status, ) - context: "ImageAnnotationContext" = proto.Field( + context: 'ImageAnnotationContext' = proto.Field( proto.MESSAGE, number=21, - message="ImageAnnotationContext", + message='ImageAnnotationContext', ) @@ -1227,10 +1226,10 @@ class BatchAnnotateImagesRequest(proto.Message): keys must start with a letter. """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) parent: str = proto.Field( proto.STRING, @@ -1252,10 +1251,10 @@ class BatchAnnotateImagesResponse(proto.Message): requests within the batch. """ - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) @@ -1291,20 +1290,20 @@ class AnnotateFileRequest(proto.Message): of the file. """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) pages: MutableSequence[int] = proto.RepeatedField( proto.INT32, @@ -1332,15 +1331,15 @@ class AnnotateFileResponse(proto.Message): The ``responses`` field will not be set in this case. """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) total_pages: int = proto.Field( proto.INT32, @@ -1387,10 +1386,10 @@ class BatchAnnotateFilesRequest(proto.Message): keys must start with a letter. """ - requests: MutableSequence["AnnotateFileRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateFileRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateFileRequest", + message='AnnotateFileRequest', ) parent: str = proto.Field( proto.STRING, @@ -1414,10 +1413,10 @@ class BatchAnnotateFilesResponse(proto.Message): BatchAnnotateFilesRequest. """ - responses: MutableSequence["AnnotateFileResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateFileResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateFileResponse", + message='AnnotateFileResponse', ) @@ -1437,25 +1436,25 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=4, - message="OutputConfig", + message='OutputConfig', ) @@ -1468,10 +1467,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=1, - message="OutputConfig", + message='OutputConfig', ) @@ -1509,15 +1508,15 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): keys must start with a letter. """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=2, - message="OutputConfig", + message='OutputConfig', ) parent: str = proto.Field( proto.STRING, @@ -1539,10 +1538,10 @@ class AsyncBatchAnnotateImagesResponse(proto.Message): AsyncBatchAnnotateImagesRequest. """ - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=1, - message="OutputConfig", + message='OutputConfig', ) @@ -1578,10 +1577,10 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): keys must start with a letter. """ - requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( + requests: MutableSequence['AsyncAnnotateFileRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileRequest", + message='AsyncAnnotateFileRequest', ) parent: str = proto.Field( proto.STRING, @@ -1604,10 +1603,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( + responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileResponse", + message='AsyncAnnotateFileResponse', ) @@ -1632,10 +1631,10 @@ class InputConfig(proto.Message): are supported. Wildcards are not supported. """ - gcs_source: "GcsSource" = proto.Field( + gcs_source: 'GcsSource' = proto.Field( proto.MESSAGE, number=1, - message="GcsSource", + message='GcsSource', ) content: bytes = proto.Field( proto.BYTES, @@ -1668,10 +1667,10 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination: "GcsDestination" = proto.Field( + gcs_destination: 'GcsDestination' = proto.Field( proto.MESSAGE, number=1, - message="GcsDestination", + message='GcsDestination', ) batch_size: int = proto.Field( proto.INT32, @@ -1712,16 +1711,16 @@ class GcsDestination(proto.Message): Examples: - - File Prefix: gs://bucket-name/here/filenameprefix The - output files will be created in gs://bucket-name/here/ and - the names of the output files will begin with - "filenameprefix". + - File Prefix: gs://bucket-name/here/filenameprefix The + output files will be created in gs://bucket-name/here/ + and the names of the output files will begin with + "filenameprefix". - - Directory Prefix: gs://bucket-name/some/location/ The - output files will be created in - gs://bucket-name/some/location/ and the names of the - output files could be anything because there was no - filename prefix specified. + - Directory Prefix: gs://bucket-name/some/location/ The + output files will be created in + gs://bucket-name/some/location/ and the names of the + output files could be anything because there was no + filename prefix specified. If multiple outputs, each response is still AnnotateFileResponse, each of which contains some subset of @@ -1748,7 +1747,6 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ - class State(proto.Enum): r"""Batch operation states. diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search.py index 7b745e9b0bbb..e490d3aa3089 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search.py @@ -17,16 +17,18 @@ from typing import MutableMapping, MutableSequence -from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.vision_v1.types import geometry, product_search_service +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.protobuf import timestamp_pb2 # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1", + package='google.cloud.vision.v1', manifest={ - "ProductSearchParams", - "ProductSearchResults", + 'ProductSearchParams', + 'ProductSearchResults', }, ) @@ -194,17 +196,15 @@ class GroupedResult(proto.Message): number=1, message=geometry.BoundingPoly, ) - results: MutableSequence["ProductSearchResults.Result"] = proto.RepeatedField( + results: MutableSequence['ProductSearchResults.Result'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="ProductSearchResults.Result", + message='ProductSearchResults.Result', ) - object_annotations: MutableSequence[ - "ProductSearchResults.ObjectAnnotation" - ] = proto.RepeatedField( + object_annotations: MutableSequence['ProductSearchResults.ObjectAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="ProductSearchResults.ObjectAnnotation", + message='ProductSearchResults.ObjectAnnotation', ) index_time: timestamp_pb2.Timestamp = proto.Field( diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search_service.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search_service.py index 857fe4832ef3..b07103c83a0c 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search_service.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/product_search_service.py @@ -17,47 +17,48 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1.types import geometry from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1.types import geometry __protobuf__ = proto.module( - package="google.cloud.vision.v1", + package='google.cloud.vision.v1', manifest={ - "Product", - "ProductSet", - "ReferenceImage", - "CreateProductRequest", - "ListProductsRequest", - "ListProductsResponse", - "GetProductRequest", - "UpdateProductRequest", - "DeleteProductRequest", - "CreateProductSetRequest", - "ListProductSetsRequest", - "ListProductSetsResponse", - "GetProductSetRequest", - "UpdateProductSetRequest", - "DeleteProductSetRequest", - "CreateReferenceImageRequest", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "GetReferenceImageRequest", - "DeleteReferenceImageRequest", - "AddProductToProductSetRequest", - "RemoveProductFromProductSetRequest", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "BatchOperationMetadata", - "ProductSetPurgeConfig", - "PurgeProductsRequest", + 'Product', + 'ProductSet', + 'ReferenceImage', + 'CreateProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'CreateProductSetRequest', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'GetProductSetRequest', + 'UpdateProductSetRequest', + 'DeleteProductSetRequest', + 'CreateReferenceImageRequest', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'GetReferenceImageRequest', + 'DeleteReferenceImageRequest', + 'AddProductToProductSetRequest', + 'RemoveProductFromProductSetRequest', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'BatchOperationMetadata', + 'ProductSetPurgeConfig', + 'PurgeProductsRequest', }, ) @@ -276,10 +277,10 @@ class CreateProductRequest(proto.Message): proto.STRING, number=1, ) - product: "Product" = proto.Field( + product: 'Product' = proto.Field( proto.MESSAGE, number=2, - message="Product", + message='Product', ) product_id: str = proto.Field( proto.STRING, @@ -334,10 +335,10 @@ class ListProductsResponse(proto.Message): def raw_page(self): return self - products: MutableSequence["Product"] = proto.RepeatedField( + products: MutableSequence['Product'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Product", + message='Product', ) next_page_token: str = proto.Field( proto.STRING, @@ -377,10 +378,10 @@ class UpdateProductRequest(proto.Message): ``product_labels``, ``display_name``, and ``description``. """ - product: "Product" = proto.Field( + product: 'Product' = proto.Field( proto.MESSAGE, number=1, - message="Product", + message='Product', ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -429,10 +430,10 @@ class CreateProductSetRequest(proto.Message): proto.STRING, number=1, ) - product_set: "ProductSet" = proto.Field( + product_set: 'ProductSet' = proto.Field( proto.MESSAGE, number=2, - message="ProductSet", + message='ProductSet', ) product_set_id: str = proto.Field( proto.STRING, @@ -487,10 +488,10 @@ class ListProductSetsResponse(proto.Message): def raw_page(self): return self - product_sets: MutableSequence["ProductSet"] = proto.RepeatedField( + product_sets: MutableSequence['ProductSet'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ProductSet", + message='ProductSet', ) next_page_token: str = proto.Field( proto.STRING, @@ -529,10 +530,10 @@ class UpdateProductSetRequest(proto.Message): ``display_name``. """ - product_set: "ProductSet" = proto.Field( + product_set: 'ProductSet' = proto.Field( proto.MESSAGE, number=1, - message="ProductSet", + message='ProductSet', ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -583,10 +584,10 @@ class CreateReferenceImageRequest(proto.Message): proto.STRING, number=1, ) - reference_image: "ReferenceImage" = proto.Field( + reference_image: 'ReferenceImage' = proto.Field( proto.MESSAGE, number=2, - message="ReferenceImage", + message='ReferenceImage', ) reference_image_id: str = proto.Field( proto.STRING, @@ -647,10 +648,10 @@ class ListReferenceImagesResponse(proto.Message): def raw_page(self): return self - reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( + reference_images: MutableSequence['ReferenceImage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ReferenceImage", + message='ReferenceImage', ) page_size: int = proto.Field( proto.INT32, @@ -799,10 +800,10 @@ class ListProductsInProductSetResponse(proto.Message): def raw_page(self): return self - products: MutableSequence["Product"] = proto.RepeatedField( + products: MutableSequence['Product'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Product", + message='Product', ) next_page_token: str = proto.Field( proto.STRING, @@ -911,11 +912,11 @@ class ImportProductSetsInputConfig(proto.Message): This field is a member of `oneof`_ ``source``. """ - gcs_source: "ImportProductSetsGcsSource" = proto.Field( + gcs_source: 'ImportProductSetsGcsSource' = proto.Field( proto.MESSAGE, number=1, - oneof="source", - message="ImportProductSetsGcsSource", + oneof='source', + message='ImportProductSetsGcsSource', ) @@ -937,10 +938,10 @@ class ImportProductSetsRequest(proto.Message): proto.STRING, number=1, ) - input_config: "ImportProductSetsInputConfig" = proto.Field( + input_config: 'ImportProductSetsInputConfig' = proto.Field( proto.MESSAGE, number=2, - message="ImportProductSetsInputConfig", + message='ImportProductSetsInputConfig', ) @@ -966,10 +967,10 @@ class ImportProductSetsResponse(proto.Message): line 0. """ - reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( + reference_images: MutableSequence['ReferenceImage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ReferenceImage", + message='ReferenceImage', ) statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, @@ -996,7 +997,6 @@ class BatchOperationMetadata(proto.Message): [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. """ - class State(proto.Enum): r"""Enumerates the possible states that the batch request can be in. @@ -1090,16 +1090,16 @@ class PurgeProductsRequest(proto.Message): value to true to actually perform the purge. """ - product_set_purge_config: "ProductSetPurgeConfig" = proto.Field( + product_set_purge_config: 'ProductSetPurgeConfig' = proto.Field( proto.MESSAGE, number=2, - oneof="target", - message="ProductSetPurgeConfig", + oneof='target', + message='ProductSetPurgeConfig', ) delete_orphan_products: bool = proto.Field( proto.BOOL, number=3, - oneof="target", + oneof='target', ) parent: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/text_annotation.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/text_annotation.py index 8461cf71f80f..f1d19b2888a9 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/text_annotation.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/text_annotation.py @@ -21,15 +21,16 @@ from google.cloud.vision_v1.types import geometry + __protobuf__ = proto.module( - package="google.cloud.vision.v1", + package='google.cloud.vision.v1', manifest={ - "TextAnnotation", - "Page", - "Block", - "Paragraph", - "Word", - "Symbol", + 'TextAnnotation', + 'Page', + 'Block', + 'Paragraph', + 'Word', + 'Symbol', }, ) @@ -81,7 +82,6 @@ class DetectedBreak(proto.Message): is_prefix (bool): True if break prepends the element. """ - class BreakType(proto.Enum): r"""Enum to denote the type of break found. New line, space etc. @@ -108,10 +108,10 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( + type_: 'TextAnnotation.DetectedBreak.BreakType' = proto.Field( proto.ENUM, number=1, - enum="TextAnnotation.DetectedBreak.BreakType", + enum='TextAnnotation.DetectedBreak.BreakType', ) is_prefix: bool = proto.Field( proto.BOOL, @@ -129,23 +129,21 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence[ - "TextAnnotation.DetectedLanguage" - ] = proto.RepeatedField( + detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="TextAnnotation.DetectedLanguage", + message='TextAnnotation.DetectedLanguage', ) - detected_break: "TextAnnotation.DetectedBreak" = proto.Field( + detected_break: 'TextAnnotation.DetectedBreak' = proto.Field( proto.MESSAGE, number=2, - message="TextAnnotation.DetectedBreak", + message='TextAnnotation.DetectedBreak', ) - pages: MutableSequence["Page"] = proto.RepeatedField( + pages: MutableSequence['Page'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Page", + message='Page', ) text: str = proto.Field( proto.STRING, @@ -172,10 +170,10 @@ class Page(proto.Message): Confidence of the OCR results on the page. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) width: int = proto.Field( proto.INT32, @@ -185,10 +183,10 @@ class Page(proto.Message): proto.INT32, number=3, ) - blocks: MutableSequence["Block"] = proto.RepeatedField( + blocks: MutableSequence['Block'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="Block", + message='Block', ) confidence: float = proto.Field( proto.FLOAT, @@ -210,24 +208,24 @@ class Block(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: + - when the text is horizontal it might look like: - :: + :: - 0----1 - | | - 3----2 + 0----1 + | | + 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: + - when it's rotated 180 degrees around the top-left corner + it becomes: - :: + :: - 2----3 - | | - 1----0 + 2----3 + | | + 1----0 - and the vertex order will still be (0, 1, 2, 3). + and the vertex order will still be (0, 1, 2, 3). paragraphs (MutableSequence[google.cloud.vision_v1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). @@ -237,7 +235,6 @@ class Block(proto.Message): confidence (float): Confidence of the OCR results on the block. Range [0, 1]. """ - class BlockType(proto.Enum): r"""Type of a block (text, image etc) as identified by OCR. @@ -262,20 +259,20 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( + paragraphs: MutableSequence['Paragraph'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Paragraph", + message='Paragraph', ) block_type: BlockType = proto.Field( proto.ENUM, @@ -303,11 +300,11 @@ class Paragraph(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertex order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). words (MutableSequence[google.cloud.vision_v1.types.Word]): List of all words in this paragraph. confidence (float): @@ -315,20 +312,20 @@ class Paragraph(proto.Message): 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words: MutableSequence["Word"] = proto.RepeatedField( + words: MutableSequence['Word'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Word", + message='Word', ) confidence: float = proto.Field( proto.FLOAT, @@ -349,11 +346,11 @@ class Word(proto.Message): represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertex order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). symbols (MutableSequence[google.cloud.vision_v1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural @@ -362,20 +359,20 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols: MutableSequence["Symbol"] = proto.RepeatedField( + symbols: MutableSequence['Symbol'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Symbol", + message='Symbol', ) confidence: float = proto.Field( proto.FLOAT, @@ -397,11 +394,11 @@ class Symbol(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertex order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). text (str): The actual UTF-8 representation of the symbol. @@ -409,10 +406,10 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/types/web_detection.py b/packages/google-cloud-vision/google/cloud/vision_v1/types/web_detection.py index 11ce1af125ac..9fca05e563e0 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/types/web_detection.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/types/web_detection.py @@ -19,10 +19,11 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1", + package='google.cloud.vision.v1', manifest={ - "WebDetection", + 'WebDetection', }, ) @@ -137,19 +138,15 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) - partial_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) class WebLabel(proto.Message): diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/__init__.py index 097c67e1b303..dc578ce2e643 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/__init__.py @@ -13,11 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import sys +from google.cloud.vision_v1p1beta1 import gapic_version as package_version import google.api_core as api_core - -from google.cloud.vision_v1p1beta1 import gapic_version as package_version +import sys __version__ = package_version.__version__ @@ -28,73 +27,71 @@ # this code path once we drop support for Python 3.7 import importlib_metadata as metadata -from google.cloud.vision_helpers import VisionHelpers -from google.cloud.vision_helpers.decorators import add_single_feature_methods +from .services.image_annotator import ImageAnnotatorClient from .services.image_annotator import ImageAnnotatorAsyncClient -from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient -from .types.geometry import BoundingPoly, Position, Vertex -from .types.image_annotator import ( - AnnotateImageRequest, - AnnotateImageResponse, - BatchAnnotateImagesRequest, - BatchAnnotateImagesResponse, - ColorInfo, - CropHint, - CropHintsAnnotation, - CropHintsParams, - DominantColorsAnnotation, - EntityAnnotation, - FaceAnnotation, - Feature, - Image, - ImageContext, - ImageProperties, - ImageSource, - LatLongRect, - Likelihood, - LocationInfo, - Property, - SafeSearchAnnotation, - TextDetectionParams, - WebDetectionParams, -) -from .types.text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word + +from .types.geometry import BoundingPoly +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import Image +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import LatLongRect +from .types.image_annotator import LocationInfo +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import TextDetectionParams +from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word from .types.web_detection import WebDetection -if hasattr(api_core, "check_python_version") and hasattr( - api_core, "check_dependency_versions" -): # pragma: NO COVER - api_core.check_python_version("google.cloud.vision_v1p1beta1") # type: ignore - api_core.check_dependency_versions("google.cloud.vision_v1p1beta1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.cloud.vision_v1p1beta1") # type: ignore + api_core.check_dependency_versions("google.cloud.vision_v1p1beta1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: - import sys import warnings + import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.vision_v1p1beta1" if sys.version_info < (3, 9): - warnings.warn( - "You are using a non-supported Python version " - + f"({_py_version_str}). Google will not post any further " - + f"updates to {_package_label} supporting this Python version. " - + "Please upgrade to the latest Python version, or at " - + f"least to Python 3.9, and then update {_package_label}.", - FutureWarning, - ) + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning) if sys.version_info[:2] == (3, 9): - warnings.warn( - f"You are using a Python version ({_py_version_str}) " - + f"which Google will stop supporting in {_package_label} in " - + "January 2026. Please " - + "upgrade to the latest Python version, or at " - + "least to Python 3.10, before then, and " - + f"then update {_package_label}.", - FutureWarning, - ) + warnings.warn(f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -132,71 +129,60 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn( - f"Package {_package_label} depends on " - + f"{_dependency_package}, currently installed at version " - + f"{_version_used_string}. Future updates to " - + f"{_package_label} will require {_dependency_package} at " - + f"version {_next_supported_version} or higher{_recommendation}." - + " Please ensure " - + "that either (a) your Python environment doesn't pin the " - + f"version of {_dependency_package}, so that updates to " - + f"{_package_label} can require the higher version, or " - + "(b) you manually update your Python environment to use at " - + f"least version {_next_supported_version} of " - + f"{_dependency_package}.", - FutureWarning, - ) + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) except Exception: - warnings.warn( - "Could not determine the version of Python " - + "currently being used. To continue receiving " - + "updates for {_package_label}, ensure you are " - + "using a supported version of Python; see " - + "https://devguide.python.org/versions/" - ) - - -@add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): - __doc__ = IacImageAnnotatorClient.__doc__ - Feature = Feature - + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") __all__ = ( - "ImageAnnotatorAsyncClient", - "AnnotateImageRequest", - "AnnotateImageResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "Block", - "BoundingPoly", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "Image", - "ImageAnnotatorClient", - "ImageContext", - "ImageProperties", - "ImageSource", - "LatLongRect", - "Likelihood", - "LocationInfo", - "Page", - "Paragraph", - "Position", - "Property", - "SafeSearchAnnotation", - "Symbol", - "TextAnnotation", - "TextDetectionParams", - "Vertex", - "WebDetection", - "WebDetectionParams", - "Word", + 'ImageAnnotatorAsyncClient', +'AnnotateImageRequest', +'AnnotateImageResponse', +'BatchAnnotateImagesRequest', +'BatchAnnotateImagesResponse', +'Block', +'BoundingPoly', +'ColorInfo', +'CropHint', +'CropHintsAnnotation', +'CropHintsParams', +'DominantColorsAnnotation', +'EntityAnnotation', +'FaceAnnotation', +'Feature', +'Image', +'ImageAnnotatorClient', +'ImageContext', +'ImageProperties', +'ImageSource', +'LatLongRect', +'Likelihood', +'LocationInfo', +'Page', +'Paragraph', +'Position', +'Property', +'SafeSearchAnnotation', +'Symbol', +'TextAnnotation', +'TextDetectionParams', +'Vertex', +'WebDetection', +'WebDetectionParams', +'Word', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py index c7f40549e472..b1663fdd632d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ImageAnnotatorAsyncClient from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient __all__ = ( - "ImageAnnotatorClient", - "ImageAnnotatorAsyncClient", + 'ImageAnnotatorClient', + 'ImageAnnotatorAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py index 859362be169a..b19bdef55058 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from google.cloud.vision_v1p1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p1beta1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -45,21 +35,18 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator - -from .client import ImageAnnotatorClient -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ImageAnnotatorAsyncClient: """Service that performs Google Cloud Vision API detection tasks over client images, such as face, landmark, logo, label, and @@ -76,30 +63,16 @@ class ImageAnnotatorAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = ImageAnnotatorClient._DEFAULT_UNIVERSE - common_billing_account_path = staticmethod( - ImageAnnotatorClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ImageAnnotatorClient.parse_common_billing_account_path - ) + common_billing_account_path = staticmethod(ImageAnnotatorClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageAnnotatorClient.parse_common_billing_account_path) common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) - parse_common_folder_path = staticmethod( - ImageAnnotatorClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ImageAnnotatorClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ImageAnnotatorClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ImageAnnotatorClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageAnnotatorClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageAnnotatorClient.parse_common_organization_path) common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) - parse_common_project_path = staticmethod( - ImageAnnotatorClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ImageAnnotatorClient.parse_common_project_path) common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) - parse_common_location_path = staticmethod( - ImageAnnotatorClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ImageAnnotatorClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -135,9 +108,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -200,16 +171,12 @@ def universe_domain(self) -> str: get_transport_class = ImageAnnotatorClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator async client. Args: @@ -264,43 +231,31 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p1beta1.ImageAnnotatorAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - async def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + async def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -358,14 +313,10 @@ async def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -379,9 +330,7 @@ async def sample_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -403,13 +352,12 @@ async def __aenter__(self) -> "ImageAnnotatorAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorAsyncClient",) +__all__ = ( + "ImageAnnotatorAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/client.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/client.py index bba40b715ef0..da22815ef5b9 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1p1beta1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p1beta1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -62,8 +49,7 @@ _LOGGER = std_logging.getLogger(__name__) from google.cloud.vision_v1p1beta1.types import image_annotator - -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -76,18 +62,14 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] _transport_registry["grpc"] = ImageAnnotatorGrpcTransport _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport _transport_registry["rest"] = ImageAnnotatorRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ImageAnnotatorTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. Args: @@ -163,16 +145,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -211,7 +191,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -228,86 +209,62 @@ def transport(self) -> ImageAnnotatorTransport: return self._transport @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -339,18 +296,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ImageAnnotatorClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -363,9 +316,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -390,9 +341,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -415,9 +364,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -433,25 +380,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -487,18 +426,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -531,16 +467,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator client. Args: @@ -595,24 +527,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ImageAnnotatorClient._read_environment_variables() - self._client_cert_source = ImageAnnotatorClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ImageAnnotatorClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageAnnotatorClient._read_environment_variables() + self._client_cert_source = ImageAnnotatorClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageAnnotatorClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -623,9 +545,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -634,10 +554,8 @@ def __init__( if transport_provided: # transport is a ImageAnnotatorTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -646,29 +564,20 @@ def __init__( self._transport = cast(ImageAnnotatorTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ImageAnnotatorClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ImageAnnotatorClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport] - ] = ( + transport_init: Union[Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport]] = ( ImageAnnotatorClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ImageAnnotatorTransport], transport) @@ -687,41 +596,28 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p1beta1.ImageAnnotatorClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -779,14 +675,10 @@ def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -829,11 +721,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorClient",) +__all__ = ( + "ImageAnnotatorClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py index 1de28b3fb87a..d3a583db5759 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] -_transport_registry["grpc"] = ImageAnnotatorGrpcTransport -_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport -_transport_registry["rest"] = ImageAnnotatorRestTransport +_transport_registry['grpc'] = ImageAnnotatorGrpcTransport +_transport_registry['grpc_asyncio'] = ImageAnnotatorGrpcAsyncIOTransport +_transport_registry['rest'] = ImageAnnotatorRestTransport __all__ = ( - "ImageAnnotatorTransport", - "ImageAnnotatorGrpcTransport", - "ImageAnnotatorGrpcAsyncIOTransport", - "ImageAnnotatorRestTransport", - "ImageAnnotatorRestInterceptor", + 'ImageAnnotatorTransport', + 'ImageAnnotatorGrpcTransport', + 'ImageAnnotatorGrpcAsyncIOTransport', + 'ImageAnnotatorRestTransport', + 'ImageAnnotatorRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py index aaa523f9a02a..ee5cc98433e8 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py @@ -16,21 +16,20 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1p1beta1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p1beta1 import gapic_version as package_version from google.cloud.vision_v1p1beta1.types import image_annotator -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -40,25 +39,24 @@ class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -85,8 +83,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -95,38 +91,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -151,27 +140,24 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Union[ - image_annotator.BatchAnnotateImagesResponse, - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Union[ + image_annotator.BatchAnnotateImagesResponse, + Awaitable[image_annotator.BatchAnnotateImagesResponse] + ]]: raise NotImplementedError() @property @@ -179,4 +165,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ImageAnnotatorTransport",) +__all__ = ( + 'ImageAnnotatorTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py index 7566cfe34a44..d0df4cbf82b2 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py @@ -16,25 +16,25 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,9 +44,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -67,7 +65,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,11 +76,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -97,7 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "rpcName": client_call_details.method, "response": grpc_response, @@ -122,26 +116,23 @@ class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -264,23 +255,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -316,21 +303,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -346,13 +331,13 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] def close(self): self._logged_channel.close() @@ -362,4 +347,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ImageAnnotatorGrpcTransport",) +__all__ = ( + 'ImageAnnotatorGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py index 4d9a6f918369..999942d0ebea 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1p1beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,13 +46,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -73,7 +69,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -84,11 +80,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -103,7 +95,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -133,15 +125,13 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -172,26 +162,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -316,9 +304,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -333,12 +319,9 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse]]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -354,16 +337,16 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.batch_annotate_images: self._wrap_method( self.batch_annotate_images, @@ -395,4 +378,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) +__all__ = ( + 'ImageAnnotatorGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest.py index e48eb01b6c98..75fc4c20c3f6 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest.py @@ -13,25 +13,31 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore +from google.auth.transport.requests import AuthorizedSession # 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 gapic_v1, rest_helpers, rest_streaming from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf + from google.protobuf import json_format + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1p1beta1.types import image_annotator -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + from .rest_base import _BaseImageAnnotatorRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -40,7 +46,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -85,15 +90,7 @@ def post_batch_annotate_images(self, response): """ - - def pre_batch_annotate_images( - self, - request: image_annotator.BatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -101,9 +98,7 @@ def pre_batch_annotate_images( """ return request, metadata - def post_batch_annotate_images( - self, response: image_annotator.BatchAnnotateImagesResponse - ) -> image_annotator.BatchAnnotateImagesResponse: + def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImagesResponse) -> image_annotator.BatchAnnotateImagesResponse: """Post-rpc interceptor for batch_annotate_images DEPRECATED. Please use the `post_batch_annotate_images_with_metadata` @@ -116,14 +111,7 @@ def post_batch_annotate_images( """ return response - def post_batch_annotate_images_with_metadata( - self, - response: image_annotator.BatchAnnotateImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_images_with_metadata(self, response: image_annotator.BatchAnnotateImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -161,21 +149,20 @@ class ImageAnnotatorRestTransport(_BaseImageAnnotatorRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ImageAnnotatorRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ImageAnnotatorRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -219,20 +206,16 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + self._credentials, default_host=self.DEFAULT_HOST) if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) self._interceptor = interceptor or ImageAnnotatorRestInterceptor() self._prep_wrapped_messages(client_info) - class _BatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -244,29 +227,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Call the batch annotate images method over HTTP. Args: @@ -288,46 +269,32 @@ def __call__( """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p1beta1.ImageAnnotatorClient.BatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "httpRequest": http_request, @@ -336,15 +303,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -359,26 +318,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateImagesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p1beta1.ImageAnnotatorClient.batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p1beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "metadata": http_response["headers"], @@ -388,15 +341,12 @@ def __call__( return resp @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: # 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._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -406,4 +356,6 @@ def close(self): self._session.close() -__all__ = ("ImageAnnotatorRestTransport",) +__all__=( + 'ImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest_base.py index 74b435f0b046..09b70d889133 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/services/image_annotator/transports/rest_base.py @@ -14,16 +14,18 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.protobuf import json_format from google.cloud.vision_v1p1beta1.types import image_annotator -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport - class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): """Base REST backend transport for ImageAnnotator. @@ -38,16 +40,14 @@ class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -71,9 +71,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -84,31 +82,27 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p1beta1/images:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/images:annotate', + 'body': '*', + }, ] return http_options @@ -123,26 +117,22 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__ = ("_BaseImageAnnotatorRestTransport",) +__all__=( + '_BaseImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/__init__.py index 16f754224295..731d736166eb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/__init__.py @@ -13,7 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .geometry import BoundingPoly, Position, Vertex +from .geometry import ( + BoundingPoly, + Position, + Vertex, +) from .image_annotator import ( AnnotateImageRequest, AnnotateImageResponse, @@ -32,48 +36,57 @@ ImageProperties, ImageSource, LatLongRect, - Likelihood, LocationInfo, Property, SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, + Likelihood, +) +from .text_annotation import ( + Block, + Page, + Paragraph, + Symbol, + TextAnnotation, + Word, +) +from .web_detection import ( + WebDetection, ) -from .text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word -from .web_detection import WebDetection __all__ = ( - "BoundingPoly", - "Position", - "Vertex", - "AnnotateImageRequest", - "AnnotateImageResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "Image", - "ImageContext", - "ImageProperties", - "ImageSource", - "LatLongRect", - "LocationInfo", - "Property", - "SafeSearchAnnotation", - "TextDetectionParams", - "WebDetectionParams", - "Likelihood", - "Block", - "Page", - "Paragraph", - "Symbol", - "TextAnnotation", - "Word", - "WebDetection", + 'BoundingPoly', + 'Position', + 'Vertex', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'ColorInfo', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'DominantColorsAnnotation', + 'EntityAnnotation', + 'FaceAnnotation', + 'Feature', + 'Image', + 'ImageContext', + 'ImageProperties', + 'ImageSource', + 'LatLongRect', + 'LocationInfo', + 'Property', + 'SafeSearchAnnotation', + 'TextDetectionParams', + 'WebDetectionParams', + 'Likelihood', + 'Block', + 'Page', + 'Paragraph', + 'Symbol', + 'TextAnnotation', + 'Word', + 'WebDetection', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/geometry.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/geometry.py index 47caffc618a5..044076dad07e 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/geometry.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/geometry.py @@ -19,12 +19,13 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p1beta1", + package='google.cloud.vision.v1p1beta1', manifest={ - "Vertex", - "BoundingPoly", - "Position", + 'Vertex', + 'BoundingPoly', + 'Position', }, ) @@ -59,10 +60,10 @@ class BoundingPoly(proto.Message): The bounding polygon vertices. """ - vertices: MutableSequence["Vertex"] = proto.RepeatedField( + vertices: MutableSequence['Vertex'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Vertex", + message='Vertex', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/image_annotator.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/image_annotator.py index 5d1e6d68c11e..80e8feadba5d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/image_annotator.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/image_annotator.py @@ -17,40 +17,42 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1p1beta1.types import geometry +from google.cloud.vision_v1p1beta1.types import text_annotation +from google.cloud.vision_v1p1beta1.types import web_detection as gcv_web_detection from google.rpc import status_pb2 # type: ignore from google.type import color_pb2 # type: ignore from google.type import latlng_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1p1beta1.types import web_detection as gcv_web_detection -from google.cloud.vision_v1p1beta1.types import geometry, text_annotation __protobuf__ = proto.module( - package="google.cloud.vision.v1p1beta1", + package='google.cloud.vision.v1p1beta1', manifest={ - "Likelihood", - "Feature", - "ImageSource", - "Image", - "FaceAnnotation", - "LocationInfo", - "Property", - "EntityAnnotation", - "SafeSearchAnnotation", - "LatLongRect", - "ColorInfo", - "DominantColorsAnnotation", - "ImageProperties", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "WebDetectionParams", - "TextDetectionParams", - "ImageContext", - "AnnotateImageRequest", - "AnnotateImageResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", + 'Likelihood', + 'Feature', + 'ImageSource', + 'Image', + 'FaceAnnotation', + 'LocationInfo', + 'Property', + 'EntityAnnotation', + 'SafeSearchAnnotation', + 'LatLongRect', + 'ColorInfo', + 'DominantColorsAnnotation', + 'ImageProperties', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'WebDetectionParams', + 'TextDetectionParams', + 'ImageContext', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', }, ) @@ -105,7 +107,6 @@ class Feature(proto.Message): ``TEXT_DETECTION`` also support "builtin/weekly" for the bleeding edge release updated weekly. """ - class Type(proto.Enum): r"""Type of image feature. @@ -217,10 +218,10 @@ class Image(proto.Message): proto.BYTES, number=1, ) - source: "ImageSource" = proto.Field( + source: 'ImageSource' = proto.Field( proto.MESSAGE, number=2, - message="ImageSource", + message='ImageSource', ) @@ -290,7 +291,6 @@ class Landmark(proto.Message): position (google.cloud.vision_v1p1beta1.types.Position): Face landmark position. """ - class Type(proto.Enum): r"""Face landmark (feature) type. Left and right are defined from the vantage of the viewer of the image without considering mirror @@ -406,10 +406,10 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_: "FaceAnnotation.Landmark.Type" = proto.Field( + type_: 'FaceAnnotation.Landmark.Type' = proto.Field( proto.ENUM, number=3, - enum="FaceAnnotation.Landmark.Type", + enum='FaceAnnotation.Landmark.Type', ) position: geometry.Position = proto.Field( proto.MESSAGE, @@ -452,40 +452,40 @@ class Type(proto.Enum): proto.FLOAT, number=8, ) - joy_likelihood: "Likelihood" = proto.Field( + joy_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) - sorrow_likelihood: "Likelihood" = proto.Field( + sorrow_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=10, - enum="Likelihood", + enum='Likelihood', ) - anger_likelihood: "Likelihood" = proto.Field( + anger_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=11, - enum="Likelihood", + enum='Likelihood', ) - surprise_likelihood: "Likelihood" = proto.Field( + surprise_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=12, - enum="Likelihood", + enum='Likelihood', ) - under_exposed_likelihood: "Likelihood" = proto.Field( + under_exposed_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=13, - enum="Likelihood", + enum='Likelihood', ) - blurred_likelihood: "Likelihood" = proto.Field( + blurred_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=14, - enum="Likelihood", + enum='Likelihood', ) - headwear_likelihood: "Likelihood" = proto.Field( + headwear_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=15, - enum="Likelihood", + enum='Likelihood', ) @@ -603,15 +603,15 @@ class EntityAnnotation(proto.Message): number=7, message=geometry.BoundingPoly, ) - locations: MutableSequence["LocationInfo"] = proto.RepeatedField( + locations: MutableSequence['LocationInfo'] = proto.RepeatedField( proto.MESSAGE, number=8, - message="LocationInfo", + message='LocationInfo', ) - properties: MutableSequence["Property"] = proto.RepeatedField( + properties: MutableSequence['Property'] = proto.RepeatedField( proto.MESSAGE, number=9, - message="Property", + message='Property', ) @@ -644,30 +644,30 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult: "Likelihood" = proto.Field( + adult: 'Likelihood' = proto.Field( proto.ENUM, number=1, - enum="Likelihood", + enum='Likelihood', ) - spoof: "Likelihood" = proto.Field( + spoof: 'Likelihood' = proto.Field( proto.ENUM, number=2, - enum="Likelihood", + enum='Likelihood', ) - medical: "Likelihood" = proto.Field( + medical: 'Likelihood' = proto.Field( proto.ENUM, number=3, - enum="Likelihood", + enum='Likelihood', ) - violence: "Likelihood" = proto.Field( + violence: 'Likelihood' = proto.Field( proto.ENUM, number=4, - enum="Likelihood", + enum='Likelihood', ) - racy: "Likelihood" = proto.Field( + racy: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) @@ -731,10 +731,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence["ColorInfo"] = proto.RepeatedField( + colors: MutableSequence['ColorInfo'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ColorInfo", + message='ColorInfo', ) @@ -747,10 +747,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: "DominantColorsAnnotation" = proto.Field( + dominant_colors: 'DominantColorsAnnotation' = proto.Field( proto.MESSAGE, number=1, - message="DominantColorsAnnotation", + message='DominantColorsAnnotation', ) @@ -794,10 +794,10 @@ class CropHintsAnnotation(proto.Message): Crop hint results. """ - crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( + crop_hints: MutableSequence['CropHint'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="CropHint", + message='CropHint', ) @@ -888,29 +888,29 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect: "LatLongRect" = proto.Field( + lat_long_rect: 'LatLongRect' = proto.Field( proto.MESSAGE, number=1, - message="LatLongRect", + message='LatLongRect', ) language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params: "CropHintsParams" = proto.Field( + crop_hints_params: 'CropHintsParams' = proto.Field( proto.MESSAGE, number=4, - message="CropHintsParams", + message='CropHintsParams', ) - web_detection_params: "WebDetectionParams" = proto.Field( + web_detection_params: 'WebDetectionParams' = proto.Field( proto.MESSAGE, number=6, - message="WebDetectionParams", + message='WebDetectionParams', ) - text_detection_params: "TextDetectionParams" = proto.Field( + text_detection_params: 'TextDetectionParams' = proto.Field( proto.MESSAGE, number=12, - message="TextDetectionParams", + message='TextDetectionParams', ) @@ -928,20 +928,20 @@ class AnnotateImageRequest(proto.Message): image. """ - image: "Image" = proto.Field( + image: 'Image' = proto.Field( proto.MESSAGE, number=1, - message="Image", + message='Image', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) @@ -987,50 +987,50 @@ class AnnotateImageResponse(proto.Message): correct, even when ``error`` is set. """ - face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( + face_annotations: MutableSequence['FaceAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="FaceAnnotation", + message='FaceAnnotation', ) - landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + landmark_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="EntityAnnotation", + message='EntityAnnotation', ) - logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + logo_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="EntityAnnotation", + message='EntityAnnotation', ) - label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + label_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="EntityAnnotation", + message='EntityAnnotation', ) - text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + text_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="EntityAnnotation", + message='EntityAnnotation', ) full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation: "SafeSearchAnnotation" = proto.Field( + safe_search_annotation: 'SafeSearchAnnotation' = proto.Field( proto.MESSAGE, number=6, - message="SafeSearchAnnotation", + message='SafeSearchAnnotation', ) - image_properties_annotation: "ImageProperties" = proto.Field( + image_properties_annotation: 'ImageProperties' = proto.Field( proto.MESSAGE, number=8, - message="ImageProperties", + message='ImageProperties', ) - crop_hints_annotation: "CropHintsAnnotation" = proto.Field( + crop_hints_annotation: 'CropHintsAnnotation' = proto.Field( proto.MESSAGE, number=11, - message="CropHintsAnnotation", + message='CropHintsAnnotation', ) web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, @@ -1054,10 +1054,10 @@ class BatchAnnotateImagesRequest(proto.Message): requests for this batch. """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) @@ -1070,10 +1070,10 @@ class BatchAnnotateImagesResponse(proto.Message): requests within the batch. """ - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/text_annotation.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/text_annotation.py index 6a1893ff64f2..2a88de5c5d42 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/text_annotation.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/text_annotation.py @@ -21,15 +21,16 @@ from google.cloud.vision_v1p1beta1.types import geometry + __protobuf__ = proto.module( - package="google.cloud.vision.v1p1beta1", + package='google.cloud.vision.v1p1beta1', manifest={ - "TextAnnotation", - "Page", - "Block", - "Paragraph", - "Word", - "Symbol", + 'TextAnnotation', + 'Page', + 'Block', + 'Paragraph', + 'Word', + 'Symbol', }, ) @@ -81,7 +82,6 @@ class DetectedBreak(proto.Message): is_prefix (bool): True if break prepends the element. """ - class BreakType(proto.Enum): r"""Enum to denote the type of break found. New line, space etc. @@ -108,10 +108,10 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( + type_: 'TextAnnotation.DetectedBreak.BreakType' = proto.Field( proto.ENUM, number=1, - enum="TextAnnotation.DetectedBreak.BreakType", + enum='TextAnnotation.DetectedBreak.BreakType', ) is_prefix: bool = proto.Field( proto.BOOL, @@ -129,23 +129,21 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence[ - "TextAnnotation.DetectedLanguage" - ] = proto.RepeatedField( + detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="TextAnnotation.DetectedLanguage", + message='TextAnnotation.DetectedLanguage', ) - detected_break: "TextAnnotation.DetectedBreak" = proto.Field( + detected_break: 'TextAnnotation.DetectedBreak' = proto.Field( proto.MESSAGE, number=2, - message="TextAnnotation.DetectedBreak", + message='TextAnnotation.DetectedBreak', ) - pages: MutableSequence["Page"] = proto.RepeatedField( + pages: MutableSequence['Page'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Page", + message='Page', ) text: str = proto.Field( proto.STRING, @@ -170,10 +168,10 @@ class Page(proto.Message): Confidence of the OCR results on the page. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) width: int = proto.Field( proto.INT32, @@ -183,10 +181,10 @@ class Page(proto.Message): proto.INT32, number=3, ) - blocks: MutableSequence["Block"] = proto.RepeatedField( + blocks: MutableSequence['Block'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="Block", + message='Block', ) confidence: float = proto.Field( proto.FLOAT, @@ -208,11 +206,11 @@ class Block(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). paragraphs (MutableSequence[google.cloud.vision_v1p1beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). @@ -222,7 +220,6 @@ class Block(proto.Message): confidence (float): Confidence of the OCR results on the block. Range [0, 1]. """ - class BlockType(proto.Enum): r"""Type of a block (text, image etc) as identified by OCR. @@ -247,20 +244,20 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( + paragraphs: MutableSequence['Paragraph'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Paragraph", + message='Paragraph', ) block_type: BlockType = proto.Field( proto.ENUM, @@ -288,11 +285,11 @@ class Paragraph(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). words (MutableSequence[google.cloud.vision_v1p1beta1.types.Word]): List of words in this paragraph. confidence (float): @@ -300,20 +297,20 @@ class Paragraph(proto.Message): 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words: MutableSequence["Word"] = proto.RepeatedField( + words: MutableSequence['Word'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Word", + message='Word', ) confidence: float = proto.Field( proto.FLOAT, @@ -334,11 +331,11 @@ class Word(proto.Message): represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). symbols (MutableSequence[google.cloud.vision_v1p1beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural @@ -347,20 +344,20 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols: MutableSequence["Symbol"] = proto.RepeatedField( + symbols: MutableSequence['Symbol'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Symbol", + message='Symbol', ) confidence: float = proto.Field( proto.FLOAT, @@ -382,11 +379,11 @@ class Symbol(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). text (str): The actual UTF-8 representation of the symbol. @@ -394,10 +391,10 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/web_detection.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/web_detection.py index bdfaf20fc558..286fb9ef4fb6 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/web_detection.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/types/web_detection.py @@ -19,10 +19,11 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p1beta1", + package='google.cloud.vision.v1p1beta1', manifest={ - "WebDetection", + 'WebDetection', }, ) @@ -135,19 +136,15 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) - partial_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) class WebLabel(proto.Message): diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/__init__.py index 38b15b5dabec..ad6f9a79441a 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/__init__.py @@ -13,11 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import sys +from google.cloud.vision_v1p2beta1 import gapic_version as package_version import google.api_core as api_core - -from google.cloud.vision_v1p2beta1 import gapic_version as package_version +import sys __version__ = package_version.__version__ @@ -28,84 +27,83 @@ # this code path once we drop support for Python 3.7 import importlib_metadata as metadata -from google.cloud.vision_helpers import VisionHelpers -from google.cloud.vision_helpers.decorators import add_single_feature_methods +from .services.image_annotator import ImageAnnotatorClient from .services.image_annotator import ImageAnnotatorAsyncClient -from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient -from .types.geometry import BoundingPoly, NormalizedVertex, Position, Vertex -from .types.image_annotator import ( - AnnotateFileResponse, - AnnotateImageRequest, - AnnotateImageResponse, - AsyncAnnotateFileRequest, - AsyncAnnotateFileResponse, - AsyncBatchAnnotateFilesRequest, - AsyncBatchAnnotateFilesResponse, - BatchAnnotateImagesRequest, - BatchAnnotateImagesResponse, - ColorInfo, - CropHint, - CropHintsAnnotation, - CropHintsParams, - DominantColorsAnnotation, - EntityAnnotation, - FaceAnnotation, - Feature, - GcsDestination, - GcsSource, - Image, - ImageAnnotationContext, - ImageContext, - ImageProperties, - ImageSource, - InputConfig, - LatLongRect, - Likelihood, - LocationInfo, - OperationMetadata, - OutputConfig, - Property, - SafeSearchAnnotation, - TextDetectionParams, - WebDetectionParams, -) -from .types.text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word + +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import TextDetectionParams +from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word from .types.web_detection import WebDetection -if hasattr(api_core, "check_python_version") and hasattr( - api_core, "check_dependency_versions" -): # pragma: NO COVER - api_core.check_python_version("google.cloud.vision_v1p2beta1") # type: ignore - api_core.check_dependency_versions("google.cloud.vision_v1p2beta1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.cloud.vision_v1p2beta1") # type: ignore + api_core.check_dependency_versions("google.cloud.vision_v1p2beta1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: - import sys import warnings + import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.vision_v1p2beta1" if sys.version_info < (3, 9): - warnings.warn( - "You are using a non-supported Python version " - + f"({_py_version_str}). Google will not post any further " - + f"updates to {_package_label} supporting this Python version. " - + "Please upgrade to the latest Python version, or at " - + f"least to Python 3.9, and then update {_package_label}.", - FutureWarning, - ) + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning) if sys.version_info[:2] == (3, 9): - warnings.warn( - f"You are using a Python version ({_py_version_str}) " - + f"which Google will stop supporting in {_package_label} in " - + "January 2026. Please " - + "upgrade to the latest Python version, or at " - + "least to Python 3.10, before then, and " - + f"then update {_package_label}.", - FutureWarning, - ) + warnings.warn(f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -143,83 +141,72 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn( - f"Package {_package_label} depends on " - + f"{_dependency_package}, currently installed at version " - + f"{_version_used_string}. Future updates to " - + f"{_package_label} will require {_dependency_package} at " - + f"version {_next_supported_version} or higher{_recommendation}." - + " Please ensure " - + "that either (a) your Python environment doesn't pin the " - + f"version of {_dependency_package}, so that updates to " - + f"{_package_label} can require the higher version, or " - + "(b) you manually update your Python environment to use at " - + f"least version {_next_supported_version} of " - + f"{_dependency_package}.", - FutureWarning, - ) + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) except Exception: - warnings.warn( - "Could not determine the version of Python " - + "currently being used. To continue receiving " - + "updates for {_package_label}, ensure you are " - + "using a supported version of Python; see " - + "https://devguide.python.org/versions/" - ) - - -@add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): - __doc__ = IacImageAnnotatorClient.__doc__ - Feature = Feature - + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") __all__ = ( - "ImageAnnotatorAsyncClient", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "Block", - "BoundingPoly", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "Image", - "ImageAnnotationContext", - "ImageAnnotatorClient", - "ImageContext", - "ImageProperties", - "ImageSource", - "InputConfig", - "LatLongRect", - "Likelihood", - "LocationInfo", - "NormalizedVertex", - "OperationMetadata", - "OutputConfig", - "Page", - "Paragraph", - "Position", - "Property", - "SafeSearchAnnotation", - "Symbol", - "TextAnnotation", - "TextDetectionParams", - "Vertex", - "WebDetection", - "WebDetectionParams", - "Word", + 'ImageAnnotatorAsyncClient', +'AnnotateFileResponse', +'AnnotateImageRequest', +'AnnotateImageResponse', +'AsyncAnnotateFileRequest', +'AsyncAnnotateFileResponse', +'AsyncBatchAnnotateFilesRequest', +'AsyncBatchAnnotateFilesResponse', +'BatchAnnotateImagesRequest', +'BatchAnnotateImagesResponse', +'Block', +'BoundingPoly', +'ColorInfo', +'CropHint', +'CropHintsAnnotation', +'CropHintsParams', +'DominantColorsAnnotation', +'EntityAnnotation', +'FaceAnnotation', +'Feature', +'GcsDestination', +'GcsSource', +'Image', +'ImageAnnotationContext', +'ImageAnnotatorClient', +'ImageContext', +'ImageProperties', +'ImageSource', +'InputConfig', +'LatLongRect', +'Likelihood', +'LocationInfo', +'NormalizedVertex', +'OperationMetadata', +'OutputConfig', +'Page', +'Paragraph', +'Position', +'Property', +'SafeSearchAnnotation', +'Symbol', +'TextAnnotation', +'TextDetectionParams', +'Vertex', +'WebDetection', +'WebDetectionParams', +'Word', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py index c7f40549e472..b1663fdd632d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ImageAnnotatorAsyncClient from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient __all__ = ( - "ImageAnnotatorClient", - "ImageAnnotatorAsyncClient", + 'ImageAnnotatorClient', + 'ImageAnnotatorAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py index fb5632ad071d..9a5082474f9a 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py @@ -13,32 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union import uuid +from google.cloud.vision_v1p2beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p2beta1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -47,23 +37,19 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore - from google.cloud.vision_v1p2beta1.types import image_annotator - -from .client import ImageAnnotatorClient -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ImageAnnotatorAsyncClient: """Service that performs Google Cloud Vision API detection tasks over client images, such as face, landmark, logo, label, and @@ -80,30 +66,16 @@ class ImageAnnotatorAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = ImageAnnotatorClient._DEFAULT_UNIVERSE - common_billing_account_path = staticmethod( - ImageAnnotatorClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ImageAnnotatorClient.parse_common_billing_account_path - ) + common_billing_account_path = staticmethod(ImageAnnotatorClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageAnnotatorClient.parse_common_billing_account_path) common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) - parse_common_folder_path = staticmethod( - ImageAnnotatorClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ImageAnnotatorClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ImageAnnotatorClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ImageAnnotatorClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageAnnotatorClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageAnnotatorClient.parse_common_organization_path) common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) - parse_common_project_path = staticmethod( - ImageAnnotatorClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ImageAnnotatorClient.parse_common_project_path) common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) - parse_common_location_path = staticmethod( - ImageAnnotatorClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ImageAnnotatorClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -139,9 +111,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -204,16 +174,12 @@ def universe_domain(self) -> str: get_transport_class = ImageAnnotatorClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator async client. Args: @@ -268,43 +234,31 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p2beta1.ImageAnnotatorAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - async def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + async def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -362,14 +316,10 @@ async def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -383,9 +333,7 @@ async def sample_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -401,19 +349,14 @@ async def sample_batch_annotate_images(): # Done; return the response. return response - async def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Run async image detection and annotation for a list of generic files (e.g. PDF) which may contain multiple pages and multiple images per page. Progress and results can be retrieved through @@ -484,14 +427,10 @@ async def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -505,9 +444,7 @@ async def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.async_batch_annotate_files - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.async_batch_annotate_files] # Validate the universe domain. self._client._validate_universe_domain() @@ -537,13 +474,12 @@ async def __aenter__(self) -> "ImageAnnotatorAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorAsyncClient",) +__all__ = ( + "ImageAnnotatorAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/client.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/client.py index aa9125703821..b262690942b3 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/client.py @@ -19,35 +19,23 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import uuid import warnings +from google.cloud.vision_v1p2beta1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p2beta1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -55,7 +43,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -64,10 +51,8 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore - from google.cloud.vision_v1p2beta1.types import image_annotator - -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -80,18 +65,14 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] _transport_registry["grpc"] = ImageAnnotatorGrpcTransport _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport _transport_registry["rest"] = ImageAnnotatorRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ImageAnnotatorTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. Args: @@ -167,16 +148,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -215,7 +194,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -232,86 +212,62 @@ def transport(self) -> ImageAnnotatorTransport: return self._transport @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -343,18 +299,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ImageAnnotatorClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -367,9 +319,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -394,9 +344,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -419,9 +367,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -437,25 +383,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -491,18 +429,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -535,16 +470,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator client. Args: @@ -599,24 +530,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ImageAnnotatorClient._read_environment_variables() - self._client_cert_source = ImageAnnotatorClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ImageAnnotatorClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageAnnotatorClient._read_environment_variables() + self._client_cert_source = ImageAnnotatorClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageAnnotatorClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -627,9 +548,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -638,10 +557,8 @@ def __init__( if transport_provided: # transport is a ImageAnnotatorTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -650,29 +567,20 @@ def __init__( self._transport = cast(ImageAnnotatorTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ImageAnnotatorClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ImageAnnotatorClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport] - ] = ( + transport_init: Union[Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport]] = ( ImageAnnotatorClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ImageAnnotatorTransport], transport) @@ -691,41 +599,28 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p2beta1.ImageAnnotatorClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -783,14 +678,10 @@ def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -819,19 +710,14 @@ def sample_batch_annotate_images(): # Done; return the response. return response - def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Run async image detection and annotation for a list of generic files (e.g. PDF) which may contain multiple pages and multiple images per page. Progress and results can be retrieved through @@ -902,14 +788,10 @@ def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -922,9 +804,7 @@ def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.async_batch_annotate_files - ] + rpc = self._transport._wrapped_methods[self._transport.async_batch_annotate_files] # Validate the universe domain. self._validate_universe_domain() @@ -962,11 +842,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorClient",) +__all__ = ( + "ImageAnnotatorClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py index 1de28b3fb87a..d3a583db5759 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] -_transport_registry["grpc"] = ImageAnnotatorGrpcTransport -_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport -_transport_registry["rest"] = ImageAnnotatorRestTransport +_transport_registry['grpc'] = ImageAnnotatorGrpcTransport +_transport_registry['grpc_asyncio'] = ImageAnnotatorGrpcAsyncIOTransport +_transport_registry['rest'] = ImageAnnotatorRestTransport __all__ = ( - "ImageAnnotatorTransport", - "ImageAnnotatorGrpcTransport", - "ImageAnnotatorGrpcAsyncIOTransport", - "ImageAnnotatorRestTransport", - "ImageAnnotatorRestInterceptor", + 'ImageAnnotatorTransport', + 'ImageAnnotatorGrpcTransport', + 'ImageAnnotatorGrpcAsyncIOTransport', + 'ImageAnnotatorRestTransport', + 'ImageAnnotatorRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py index 0e16cba7627b..96a26ecc7264 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py @@ -16,22 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1p2beta1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p2beta1 import gapic_version as package_version from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,25 +41,24 @@ class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -86,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -96,38 +93,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -167,14 +157,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -184,24 +174,21 @@ def operations_client(self): raise NotImplementedError() @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Union[ - image_annotator.BatchAnnotateImagesResponse, - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Union[ + image_annotator.BatchAnnotateImagesResponse, + Awaitable[image_annotator.BatchAnnotateImagesResponse] + ]]: raise NotImplementedError() @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -209,4 +196,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ImageAnnotatorTransport",) +__all__ = ( + 'ImageAnnotatorTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py index 7fe5866362e2..e2a668a6d116 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py @@ -16,26 +16,27 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -45,9 +46,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -68,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -79,11 +78,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -98,7 +93,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": client_call_details.method, "response": grpc_response, @@ -123,26 +118,23 @@ class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -266,23 +258,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -318,12 +306,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -343,12 +332,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -364,20 +350,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + operations_pb2.Operation]: r"""Return a callable for the async batch annotate files method over gRPC. Run async image detection and annotation for a list of generic @@ -398,15 +382,13 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def close(self): self._logged_channel.close() @@ -416,4 +398,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ImageAnnotatorGrpcTransport",) +__all__ = ( + 'ImageAnnotatorGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py index 41879c4326a0..98d2c16f8536 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py @@ -15,31 +15,32 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -47,13 +48,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -74,7 +71,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -85,11 +82,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -104,7 +97,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -134,15 +127,13 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -173,26 +164,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -318,9 +307,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -351,12 +338,9 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse]]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -372,21 +356,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations_pb2.Operation], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the async batch annotate files method over gRPC. Run async image detection and annotation for a list of generic @@ -407,18 +388,16 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.batch_annotate_images: self._wrap_method( self.batch_annotate_images, @@ -465,4 +444,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) +__all__ = ( + 'ImageAnnotatorGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest.py index 69fd6a6d7998..1e04a22edf86 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest.py @@ -13,26 +13,33 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -41,7 +48,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -94,15 +100,7 @@ def post_batch_annotate_images(self, response): """ - - def pre_async_batch_annotate_files( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.AsyncBatchAnnotateFilesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnnotateFilesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.AsyncBatchAnnotateFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for async_batch_annotate_files Override in a subclass to manipulate the request or metadata @@ -110,9 +108,7 @@ def pre_async_batch_annotate_files( """ return request, metadata - def post_async_batch_annotate_files( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for async_batch_annotate_files DEPRECATED. Please use the `post_async_batch_annotate_files_with_metadata` @@ -125,11 +121,7 @@ def post_async_batch_annotate_files( """ return response - def post_async_batch_annotate_files_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for async_batch_annotate_files Override in a subclass to read or manipulate the response or metadata after it @@ -144,14 +136,7 @@ def post_async_batch_annotate_files_with_metadata( """ return response, metadata - def pre_batch_annotate_images( - self, - request: image_annotator.BatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -159,9 +144,7 @@ def pre_batch_annotate_images( """ return request, metadata - def post_batch_annotate_images( - self, response: image_annotator.BatchAnnotateImagesResponse - ) -> image_annotator.BatchAnnotateImagesResponse: + def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImagesResponse) -> image_annotator.BatchAnnotateImagesResponse: """Post-rpc interceptor for batch_annotate_images DEPRECATED. Please use the `post_batch_annotate_images_with_metadata` @@ -174,14 +157,7 @@ def post_batch_annotate_images( """ return response - def post_batch_annotate_images_with_metadata( - self, - response: image_annotator.BatchAnnotateImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_images_with_metadata(self, response: image_annotator.BatchAnnotateImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -219,21 +195,20 @@ class ImageAnnotatorRestTransport(_BaseImageAnnotatorRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ImageAnnotatorRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ImageAnnotatorRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -277,11 +252,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -297,28 +271,23 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: """ # 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]]] = {} + http_options: Dict[str, List[Dict[str, str]]] = { + } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1p2beta1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p2beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AsyncBatchAnnotateFiles( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, - ImageAnnotatorRestStub, - ): + class _AsyncBatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateFiles") @@ -330,93 +299,77 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: image_annotator.AsyncBatchAnnotateFilesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the async batch annotate - files method over HTTP. - - Args: - request (~.image_annotator.AsyncBatchAnnotateFilesRequest): - The request object. Multiple async file annotation - requests are batched into a single - service call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + files method over HTTP. + + Args: + request (~.image_annotator.AsyncBatchAnnotateFilesRequest): + The request object. Multiple async file annotation + requests are batched into a single + service call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - request, metadata = self._interceptor.pre_async_batch_annotate_files( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_async_batch_annotate_files(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p2beta1.ImageAnnotatorClient.AsyncBatchAnnotateFiles", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "httpRequest": http_request, @@ -425,17 +378,7 @@ def __call__( ) # Send the request - response = ( - ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -448,24 +391,20 @@ def __call__( resp = self._interceptor.post_async_batch_annotate_files(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p2beta1.ImageAnnotatorClient.async_batch_annotate_files", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "metadata": http_response["headers"], @@ -474,10 +413,7 @@ def __call__( ) return resp - class _BatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -489,29 +425,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Call the batch annotate images method over HTTP. Args: @@ -533,46 +467,32 @@ def __call__( """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p2beta1.ImageAnnotatorClient.BatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "httpRequest": http_request, @@ -581,15 +501,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -604,26 +516,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateImagesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p2beta1.ImageAnnotatorClient.batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p2beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "metadata": http_response["headers"], @@ -633,25 +539,20 @@ def __call__( return resp @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + 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._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore + return self._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: # 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._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -661,4 +562,6 @@ def close(self): self._session.close() -__all__ = ("ImageAnnotatorRestTransport",) +__all__=( + 'ImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest_base.py index e26576904564..c024eb91195c 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/services/image_annotator/transports/rest_base.py @@ -14,16 +14,18 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1p2beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -39,16 +41,14 @@ class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -72,9 +72,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -85,31 +83,27 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAsyncBatchAnnotateFiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p2beta1/files:asyncBatchAnnotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p2beta1/files:asyncBatchAnnotate', + 'body': '*', + }, ] return http_options @@ -124,23 +118,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -149,24 +137,20 @@ class _BaseBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p2beta1/images:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p2beta1/images:annotate', + 'body': '*', + }, ] return http_options @@ -181,26 +165,22 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__ = ("_BaseImageAnnotatorRestTransport",) +__all__=( + '_BaseImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/__init__.py index 70859b5384a4..fbde77c956b4 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/__init__.py @@ -13,7 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .geometry import BoundingPoly, NormalizedVertex, Position, Vertex +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Position, + Vertex, +) from .image_annotator import ( AnnotateFileResponse, AnnotateImageRequest, @@ -41,7 +46,6 @@ ImageSource, InputConfig, LatLongRect, - Likelihood, LocationInfo, OperationMetadata, OutputConfig, @@ -49,54 +53,64 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, + Likelihood, +) +from .text_annotation import ( + Block, + Page, + Paragraph, + Symbol, + TextAnnotation, + Word, +) +from .web_detection import ( + WebDetection, ) -from .text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word -from .web_detection import WebDetection __all__ = ( - "BoundingPoly", - "NormalizedVertex", - "Position", - "Vertex", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "Image", - "ImageAnnotationContext", - "ImageContext", - "ImageProperties", - "ImageSource", - "InputConfig", - "LatLongRect", - "LocationInfo", - "OperationMetadata", - "OutputConfig", - "Property", - "SafeSearchAnnotation", - "TextDetectionParams", - "WebDetectionParams", - "Likelihood", - "Block", - "Page", - "Paragraph", - "Symbol", - "TextAnnotation", - "Word", - "WebDetection", + 'BoundingPoly', + 'NormalizedVertex', + 'Position', + 'Vertex', + 'AnnotateFileResponse', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'ColorInfo', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'DominantColorsAnnotation', + 'EntityAnnotation', + 'FaceAnnotation', + 'Feature', + 'GcsDestination', + 'GcsSource', + 'Image', + 'ImageAnnotationContext', + 'ImageContext', + 'ImageProperties', + 'ImageSource', + 'InputConfig', + 'LatLongRect', + 'LocationInfo', + 'OperationMetadata', + 'OutputConfig', + 'Property', + 'SafeSearchAnnotation', + 'TextDetectionParams', + 'WebDetectionParams', + 'Likelihood', + 'Block', + 'Page', + 'Paragraph', + 'Symbol', + 'TextAnnotation', + 'Word', + 'WebDetection', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/geometry.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/geometry.py index 269b5d8bc68c..3ebc43555d87 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/geometry.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/geometry.py @@ -19,13 +19,14 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p2beta1", + package='google.cloud.vision.v1p2beta1', manifest={ - "Vertex", - "NormalizedVertex", - "BoundingPoly", - "Position", + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + 'Position', }, ) @@ -84,15 +85,15 @@ class BoundingPoly(proto.Message): The bounding polygon normalized vertices. """ - vertices: MutableSequence["Vertex"] = proto.RepeatedField( + vertices: MutableSequence['Vertex'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Vertex", + message='Vertex', ) - normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="NormalizedVertex", + message='NormalizedVertex', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/image_annotator.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/image_annotator.py index 89143e766721..970c22c8751c 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/image_annotator.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/image_annotator.py @@ -17,52 +17,54 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1p2beta1.types import geometry +from google.cloud.vision_v1p2beta1.types import text_annotation +from google.cloud.vision_v1p2beta1.types import web_detection as gcv_web_detection from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.type import color_pb2 # type: ignore from google.type import latlng_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1p2beta1.types import web_detection as gcv_web_detection -from google.cloud.vision_v1p2beta1.types import geometry, text_annotation __protobuf__ = proto.module( - package="google.cloud.vision.v1p2beta1", + package='google.cloud.vision.v1p2beta1', manifest={ - "Likelihood", - "Feature", - "ImageSource", - "Image", - "FaceAnnotation", - "LocationInfo", - "Property", - "EntityAnnotation", - "SafeSearchAnnotation", - "LatLongRect", - "ColorInfo", - "DominantColorsAnnotation", - "ImageProperties", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "WebDetectionParams", - "TextDetectionParams", - "ImageContext", - "AnnotateImageRequest", - "ImageAnnotationContext", - "AnnotateImageResponse", - "AnnotateFileResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "InputConfig", - "OutputConfig", - "GcsSource", - "GcsDestination", - "OperationMetadata", + 'Likelihood', + 'Feature', + 'ImageSource', + 'Image', + 'FaceAnnotation', + 'LocationInfo', + 'Property', + 'EntityAnnotation', + 'SafeSearchAnnotation', + 'LatLongRect', + 'ColorInfo', + 'DominantColorsAnnotation', + 'ImageProperties', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'WebDetectionParams', + 'TextDetectionParams', + 'ImageContext', + 'AnnotateImageRequest', + 'ImageAnnotationContext', + 'AnnotateImageResponse', + 'AnnotateFileResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + 'OperationMetadata', }, ) @@ -117,7 +119,6 @@ class Feature(proto.Message): ``TEXT_DETECTION`` also support "builtin/weekly" for the bleeding edge release updated weekly. """ - class Type(proto.Enum): r"""Type of Google Cloud Vision API feature to be extracted. @@ -243,10 +244,10 @@ class Image(proto.Message): proto.BYTES, number=1, ) - source: "ImageSource" = proto.Field( + source: 'ImageSource' = proto.Field( proto.MESSAGE, number=2, - message="ImageSource", + message='ImageSource', ) @@ -316,7 +317,6 @@ class Landmark(proto.Message): position (google.cloud.vision_v1p2beta1.types.Position): Face landmark position. """ - class Type(proto.Enum): r"""Face landmark (feature) type. Left and right are defined from the vantage of the viewer of the image without considering mirror @@ -432,10 +432,10 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_: "FaceAnnotation.Landmark.Type" = proto.Field( + type_: 'FaceAnnotation.Landmark.Type' = proto.Field( proto.ENUM, number=3, - enum="FaceAnnotation.Landmark.Type", + enum='FaceAnnotation.Landmark.Type', ) position: geometry.Position = proto.Field( proto.MESSAGE, @@ -478,40 +478,40 @@ class Type(proto.Enum): proto.FLOAT, number=8, ) - joy_likelihood: "Likelihood" = proto.Field( + joy_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) - sorrow_likelihood: "Likelihood" = proto.Field( + sorrow_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=10, - enum="Likelihood", + enum='Likelihood', ) - anger_likelihood: "Likelihood" = proto.Field( + anger_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=11, - enum="Likelihood", + enum='Likelihood', ) - surprise_likelihood: "Likelihood" = proto.Field( + surprise_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=12, - enum="Likelihood", + enum='Likelihood', ) - under_exposed_likelihood: "Likelihood" = proto.Field( + under_exposed_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=13, - enum="Likelihood", + enum='Likelihood', ) - blurred_likelihood: "Likelihood" = proto.Field( + blurred_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=14, - enum="Likelihood", + enum='Likelihood', ) - headwear_likelihood: "Likelihood" = proto.Field( + headwear_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=15, - enum="Likelihood", + enum='Likelihood', ) @@ -630,15 +630,15 @@ class EntityAnnotation(proto.Message): number=7, message=geometry.BoundingPoly, ) - locations: MutableSequence["LocationInfo"] = proto.RepeatedField( + locations: MutableSequence['LocationInfo'] = proto.RepeatedField( proto.MESSAGE, number=8, - message="LocationInfo", + message='LocationInfo', ) - properties: MutableSequence["Property"] = proto.RepeatedField( + properties: MutableSequence['Property'] = proto.RepeatedField( proto.MESSAGE, number=9, - message="Property", + message='Property', ) @@ -671,30 +671,30 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult: "Likelihood" = proto.Field( + adult: 'Likelihood' = proto.Field( proto.ENUM, number=1, - enum="Likelihood", + enum='Likelihood', ) - spoof: "Likelihood" = proto.Field( + spoof: 'Likelihood' = proto.Field( proto.ENUM, number=2, - enum="Likelihood", + enum='Likelihood', ) - medical: "Likelihood" = proto.Field( + medical: 'Likelihood' = proto.Field( proto.ENUM, number=3, - enum="Likelihood", + enum='Likelihood', ) - violence: "Likelihood" = proto.Field( + violence: 'Likelihood' = proto.Field( proto.ENUM, number=4, - enum="Likelihood", + enum='Likelihood', ) - racy: "Likelihood" = proto.Field( + racy: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) @@ -758,10 +758,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence["ColorInfo"] = proto.RepeatedField( + colors: MutableSequence['ColorInfo'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ColorInfo", + message='ColorInfo', ) @@ -774,10 +774,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: "DominantColorsAnnotation" = proto.Field( + dominant_colors: 'DominantColorsAnnotation' = proto.Field( proto.MESSAGE, number=1, - message="DominantColorsAnnotation", + message='DominantColorsAnnotation', ) @@ -821,10 +821,10 @@ class CropHintsAnnotation(proto.Message): Crop hint results. """ - crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( + crop_hints: MutableSequence['CropHint'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="CropHint", + message='CropHint', ) @@ -914,29 +914,29 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect: "LatLongRect" = proto.Field( + lat_long_rect: 'LatLongRect' = proto.Field( proto.MESSAGE, number=1, - message="LatLongRect", + message='LatLongRect', ) language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params: "CropHintsParams" = proto.Field( + crop_hints_params: 'CropHintsParams' = proto.Field( proto.MESSAGE, number=4, - message="CropHintsParams", + message='CropHintsParams', ) - web_detection_params: "WebDetectionParams" = proto.Field( + web_detection_params: 'WebDetectionParams' = proto.Field( proto.MESSAGE, number=6, - message="WebDetectionParams", + message='WebDetectionParams', ) - text_detection_params: "TextDetectionParams" = proto.Field( + text_detection_params: 'TextDetectionParams' = proto.Field( proto.MESSAGE, number=12, - message="TextDetectionParams", + message='TextDetectionParams', ) @@ -954,20 +954,20 @@ class AnnotateImageRequest(proto.Message): image. """ - image: "Image" = proto.Field( + image: 'Image' = proto.Field( proto.MESSAGE, number=1, - message="Image", + message='Image', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) @@ -1040,50 +1040,50 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( + face_annotations: MutableSequence['FaceAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="FaceAnnotation", + message='FaceAnnotation', ) - landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + landmark_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="EntityAnnotation", + message='EntityAnnotation', ) - logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + logo_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="EntityAnnotation", + message='EntityAnnotation', ) - label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + label_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="EntityAnnotation", + message='EntityAnnotation', ) - text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + text_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="EntityAnnotation", + message='EntityAnnotation', ) full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation: "SafeSearchAnnotation" = proto.Field( + safe_search_annotation: 'SafeSearchAnnotation' = proto.Field( proto.MESSAGE, number=6, - message="SafeSearchAnnotation", + message='SafeSearchAnnotation', ) - image_properties_annotation: "ImageProperties" = proto.Field( + image_properties_annotation: 'ImageProperties' = proto.Field( proto.MESSAGE, number=8, - message="ImageProperties", + message='ImageProperties', ) - crop_hints_annotation: "CropHintsAnnotation" = proto.Field( + crop_hints_annotation: 'CropHintsAnnotation' = proto.Field( proto.MESSAGE, number=11, - message="CropHintsAnnotation", + message='CropHintsAnnotation', ) web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, @@ -1095,10 +1095,10 @@ class AnnotateImageResponse(proto.Message): number=9, message=status_pb2.Status, ) - context: "ImageAnnotationContext" = proto.Field( + context: 'ImageAnnotationContext' = proto.Field( proto.MESSAGE, number=21, - message="ImageAnnotationContext", + message='ImageAnnotationContext', ) @@ -1116,15 +1116,15 @@ class AnnotateFileResponse(proto.Message): the file. """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) @@ -1138,10 +1138,10 @@ class BatchAnnotateImagesRequest(proto.Message): requests for this batch. """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) @@ -1154,10 +1154,10 @@ class BatchAnnotateImagesResponse(proto.Message): requests within the batch. """ - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) @@ -1177,25 +1177,25 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=4, - message="OutputConfig", + message='OutputConfig', ) @@ -1208,10 +1208,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=1, - message="OutputConfig", + message='OutputConfig', ) @@ -1225,10 +1225,10 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): requests for this batch. """ - requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( + requests: MutableSequence['AsyncAnnotateFileRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileRequest", + message='AsyncAnnotateFileRequest', ) @@ -1242,10 +1242,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( + responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileResponse", + message='AsyncAnnotateFileResponse', ) @@ -1262,10 +1262,10 @@ class InputConfig(proto.Message): supported. Wildcards are not supported. """ - gcs_source: "GcsSource" = proto.Field( + gcs_source: 'GcsSource' = proto.Field( proto.MESSAGE, number=1, - message="GcsSource", + message='GcsSource', ) mime_type: str = proto.Field( proto.STRING, @@ -1294,10 +1294,10 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination: "GcsDestination" = proto.Field( + gcs_destination: 'GcsDestination' = proto.Field( proto.MESSAGE, number=1, - message="GcsDestination", + message='GcsDestination', ) batch_size: int = proto.Field( proto.INT32, @@ -1336,9 +1336,9 @@ class GcsDestination(proto.Message): Examples: - - File: gs://bucket-name/filename.json - - Prefix: gs://bucket-name/prefix/here/ - - File: gs://bucket-name/prefix/here + - File: gs://bucket-name/filename.json + - Prefix: gs://bucket-name/prefix/here/ + - File: gs://bucket-name/prefix/here If multiple outputs, each response is still AnnotateFileResponse, each of which contains some subset of @@ -1365,7 +1365,6 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ - class State(proto.Enum): r"""Batch operation states. diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/text_annotation.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/text_annotation.py index 1fed739872b4..fef53f89cb80 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/text_annotation.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/text_annotation.py @@ -21,15 +21,16 @@ from google.cloud.vision_v1p2beta1.types import geometry + __protobuf__ = proto.module( - package="google.cloud.vision.v1p2beta1", + package='google.cloud.vision.v1p2beta1', manifest={ - "TextAnnotation", - "Page", - "Block", - "Paragraph", - "Word", - "Symbol", + 'TextAnnotation', + 'Page', + 'Block', + 'Paragraph', + 'Word', + 'Symbol', }, ) @@ -81,7 +82,6 @@ class DetectedBreak(proto.Message): is_prefix (bool): True if break prepends the element. """ - class BreakType(proto.Enum): r"""Enum to denote the type of break found. New line, space etc. @@ -108,10 +108,10 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( + type_: 'TextAnnotation.DetectedBreak.BreakType' = proto.Field( proto.ENUM, number=1, - enum="TextAnnotation.DetectedBreak.BreakType", + enum='TextAnnotation.DetectedBreak.BreakType', ) is_prefix: bool = proto.Field( proto.BOOL, @@ -129,23 +129,21 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence[ - "TextAnnotation.DetectedLanguage" - ] = proto.RepeatedField( + detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="TextAnnotation.DetectedLanguage", + message='TextAnnotation.DetectedLanguage', ) - detected_break: "TextAnnotation.DetectedBreak" = proto.Field( + detected_break: 'TextAnnotation.DetectedBreak' = proto.Field( proto.MESSAGE, number=2, - message="TextAnnotation.DetectedBreak", + message='TextAnnotation.DetectedBreak', ) - pages: MutableSequence["Page"] = proto.RepeatedField( + pages: MutableSequence['Page'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Page", + message='Page', ) text: str = proto.Field( proto.STRING, @@ -172,10 +170,10 @@ class Page(proto.Message): Confidence of the OCR results on the page. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) width: int = proto.Field( proto.INT32, @@ -185,10 +183,10 @@ class Page(proto.Message): proto.INT32, number=3, ) - blocks: MutableSequence["Block"] = proto.RepeatedField( + blocks: MutableSequence['Block'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="Block", + message='Block', ) confidence: float = proto.Field( proto.FLOAT, @@ -210,24 +208,24 @@ class Block(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: + - when the text is horizontal it might look like: - :: + :: - 0----1 - | | - 3----2 + 0----1 + | | + 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: + - when it's rotated 180 degrees around the top-left corner + it becomes: - :: + :: - 2----3 - | | - 1----0 + 2----3 + | | + 1----0 - and the vertice order will still be (0, 1, 2, 3). + and the vertice order will still be (0, 1, 2, 3). paragraphs (MutableSequence[google.cloud.vision_v1p2beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). @@ -237,7 +235,6 @@ class Block(proto.Message): confidence (float): Confidence of the OCR results on the block. Range [0, 1]. """ - class BlockType(proto.Enum): r"""Type of a block (text, image etc) as identified by OCR. @@ -262,20 +259,20 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( + paragraphs: MutableSequence['Paragraph'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Paragraph", + message='Paragraph', ) block_type: BlockType = proto.Field( proto.ENUM, @@ -303,11 +300,11 @@ class Paragraph(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). words (MutableSequence[google.cloud.vision_v1p2beta1.types.Word]): List of words in this paragraph. confidence (float): @@ -315,20 +312,20 @@ class Paragraph(proto.Message): 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words: MutableSequence["Word"] = proto.RepeatedField( + words: MutableSequence['Word'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Word", + message='Word', ) confidence: float = proto.Field( proto.FLOAT, @@ -349,11 +346,11 @@ class Word(proto.Message): represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). symbols (MutableSequence[google.cloud.vision_v1p2beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural @@ -362,20 +359,20 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols: MutableSequence["Symbol"] = proto.RepeatedField( + symbols: MutableSequence['Symbol'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Symbol", + message='Symbol', ) confidence: float = proto.Field( proto.FLOAT, @@ -397,11 +394,11 @@ class Symbol(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). text (str): The actual UTF-8 representation of the symbol. @@ -409,10 +406,10 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/web_detection.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/web_detection.py index 648d4e415953..557f1e2b4225 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/web_detection.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/types/web_detection.py @@ -19,10 +19,11 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p2beta1", + package='google.cloud.vision.v1p2beta1', manifest={ - "WebDetection", + 'WebDetection', }, ) @@ -135,19 +136,15 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) - partial_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) class WebLabel(proto.Message): diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/__init__.py index a2e768f2a3da..6e317eaf354f 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/__init__.py @@ -13,11 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import sys +from google.cloud.vision_v1p3beta1 import gapic_version as package_version import google.api_core as api_core - -from google.cloud.vision_v1p3beta1 import gapic_version as package_version +import sys __version__ = package_version.__version__ @@ -28,118 +27,117 @@ # this code path once we drop support for Python 3.7 import importlib_metadata as metadata -from google.cloud.vision_helpers import VisionHelpers -from google.cloud.vision_helpers.decorators import add_single_feature_methods +from .services.image_annotator import ImageAnnotatorClient from .services.image_annotator import ImageAnnotatorAsyncClient -from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient -from .services.product_search import ProductSearchAsyncClient, ProductSearchClient -from .types.geometry import BoundingPoly, NormalizedVertex, Position, Vertex -from .types.image_annotator import ( - AnnotateFileResponse, - AnnotateImageRequest, - AnnotateImageResponse, - AsyncAnnotateFileRequest, - AsyncAnnotateFileResponse, - AsyncBatchAnnotateFilesRequest, - AsyncBatchAnnotateFilesResponse, - BatchAnnotateImagesRequest, - BatchAnnotateImagesResponse, - ColorInfo, - CropHint, - CropHintsAnnotation, - CropHintsParams, - DominantColorsAnnotation, - EntityAnnotation, - FaceAnnotation, - Feature, - GcsDestination, - GcsSource, - Image, - ImageAnnotationContext, - ImageContext, - ImageProperties, - ImageSource, - InputConfig, - LatLongRect, - Likelihood, - LocalizedObjectAnnotation, - LocationInfo, - OperationMetadata, - OutputConfig, - Property, - SafeSearchAnnotation, - TextDetectionParams, - WebDetectionParams, -) -from .types.product_search import ProductSearchParams, ProductSearchResults -from .types.product_search_service import ( - AddProductToProductSetRequest, - BatchOperationMetadata, - CreateProductRequest, - CreateProductSetRequest, - CreateReferenceImageRequest, - DeleteProductRequest, - DeleteProductSetRequest, - DeleteReferenceImageRequest, - GetProductRequest, - GetProductSetRequest, - GetReferenceImageRequest, - ImportProductSetsGcsSource, - ImportProductSetsInputConfig, - ImportProductSetsRequest, - ImportProductSetsResponse, - ListProductSetsRequest, - ListProductSetsResponse, - ListProductsInProductSetRequest, - ListProductsInProductSetResponse, - ListProductsRequest, - ListProductsResponse, - ListReferenceImagesRequest, - ListReferenceImagesResponse, - Product, - ProductSet, - ReferenceImage, - RemoveProductFromProductSetRequest, - UpdateProductRequest, - UpdateProductSetRequest, -) -from .types.text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word +from .services.product_search import ProductSearchClient +from .services.product_search import ProductSearchAsyncClient + +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import LocalizedObjectAnnotation +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import TextDetectionParams +from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood +from .types.product_search import ProductSearchParams +from .types.product_search import ProductSearchResults +from .types.product_search_service import AddProductToProductSetRequest +from .types.product_search_service import BatchOperationMetadata +from .types.product_search_service import CreateProductRequest +from .types.product_search_service import CreateProductSetRequest +from .types.product_search_service import CreateReferenceImageRequest +from .types.product_search_service import DeleteProductRequest +from .types.product_search_service import DeleteProductSetRequest +from .types.product_search_service import DeleteReferenceImageRequest +from .types.product_search_service import GetProductRequest +from .types.product_search_service import GetProductSetRequest +from .types.product_search_service import GetReferenceImageRequest +from .types.product_search_service import ImportProductSetsGcsSource +from .types.product_search_service import ImportProductSetsInputConfig +from .types.product_search_service import ImportProductSetsRequest +from .types.product_search_service import ImportProductSetsResponse +from .types.product_search_service import ListProductSetsRequest +from .types.product_search_service import ListProductSetsResponse +from .types.product_search_service import ListProductsInProductSetRequest +from .types.product_search_service import ListProductsInProductSetResponse +from .types.product_search_service import ListProductsRequest +from .types.product_search_service import ListProductsResponse +from .types.product_search_service import ListReferenceImagesRequest +from .types.product_search_service import ListReferenceImagesResponse +from .types.product_search_service import Product +from .types.product_search_service import ProductSet +from .types.product_search_service import ReferenceImage +from .types.product_search_service import RemoveProductFromProductSetRequest +from .types.product_search_service import UpdateProductRequest +from .types.product_search_service import UpdateProductSetRequest +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word from .types.web_detection import WebDetection -if hasattr(api_core, "check_python_version") and hasattr( - api_core, "check_dependency_versions" -): # pragma: NO COVER - api_core.check_python_version("google.cloud.vision_v1p3beta1") # type: ignore - api_core.check_dependency_versions("google.cloud.vision_v1p3beta1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.cloud.vision_v1p3beta1") # type: ignore + api_core.check_dependency_versions("google.cloud.vision_v1p3beta1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: - import sys import warnings + import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.vision_v1p3beta1" if sys.version_info < (3, 9): - warnings.warn( - "You are using a non-supported Python version " - + f"({_py_version_str}). Google will not post any further " - + f"updates to {_package_label} supporting this Python version. " - + "Please upgrade to the latest Python version, or at " - + f"least to Python 3.9, and then update {_package_label}.", - FutureWarning, - ) + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning) if sys.version_info[:2] == (3, 9): - warnings.warn( - f"You are using a Python version ({_py_version_str}) " - + f"which Google will stop supporting in {_package_label} in " - + "January 2026. Please " - + "upgrade to the latest Python version, or at " - + "least to Python 3.10, before then, and " - + f"then update {_package_label}.", - FutureWarning, - ) + warnings.warn(f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -177,117 +175,106 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn( - f"Package {_package_label} depends on " - + f"{_dependency_package}, currently installed at version " - + f"{_version_used_string}. Future updates to " - + f"{_package_label} will require {_dependency_package} at " - + f"version {_next_supported_version} or higher{_recommendation}." - + " Please ensure " - + "that either (a) your Python environment doesn't pin the " - + f"version of {_dependency_package}, so that updates to " - + f"{_package_label} can require the higher version, or " - + "(b) you manually update your Python environment to use at " - + f"least version {_next_supported_version} of " - + f"{_dependency_package}.", - FutureWarning, - ) + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) except Exception: - warnings.warn( - "Could not determine the version of Python " - + "currently being used. To continue receiving " - + "updates for {_package_label}, ensure you are " - + "using a supported version of Python; see " - + "https://devguide.python.org/versions/" - ) - - -@add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): - __doc__ = IacImageAnnotatorClient.__doc__ - Feature = Feature - + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") __all__ = ( - "ImageAnnotatorAsyncClient", - "ProductSearchAsyncClient", - "AddProductToProductSetRequest", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "BatchOperationMetadata", - "Block", - "BoundingPoly", - "ColorInfo", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "Image", - "ImageAnnotationContext", - "ImageAnnotatorClient", - "ImageContext", - "ImageProperties", - "ImageSource", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "InputConfig", - "LatLongRect", - "Likelihood", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "LocalizedObjectAnnotation", - "LocationInfo", - "NormalizedVertex", - "OperationMetadata", - "OutputConfig", - "Page", - "Paragraph", - "Position", - "Product", - "ProductSearchClient", - "ProductSearchParams", - "ProductSearchResults", - "ProductSet", - "Property", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "SafeSearchAnnotation", - "Symbol", - "TextAnnotation", - "TextDetectionParams", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Vertex", - "WebDetection", - "WebDetectionParams", - "Word", + 'ImageAnnotatorAsyncClient', + 'ProductSearchAsyncClient', +'AddProductToProductSetRequest', +'AnnotateFileResponse', +'AnnotateImageRequest', +'AnnotateImageResponse', +'AsyncAnnotateFileRequest', +'AsyncAnnotateFileResponse', +'AsyncBatchAnnotateFilesRequest', +'AsyncBatchAnnotateFilesResponse', +'BatchAnnotateImagesRequest', +'BatchAnnotateImagesResponse', +'BatchOperationMetadata', +'Block', +'BoundingPoly', +'ColorInfo', +'CreateProductRequest', +'CreateProductSetRequest', +'CreateReferenceImageRequest', +'CropHint', +'CropHintsAnnotation', +'CropHintsParams', +'DeleteProductRequest', +'DeleteProductSetRequest', +'DeleteReferenceImageRequest', +'DominantColorsAnnotation', +'EntityAnnotation', +'FaceAnnotation', +'Feature', +'GcsDestination', +'GcsSource', +'GetProductRequest', +'GetProductSetRequest', +'GetReferenceImageRequest', +'Image', +'ImageAnnotationContext', +'ImageAnnotatorClient', +'ImageContext', +'ImageProperties', +'ImageSource', +'ImportProductSetsGcsSource', +'ImportProductSetsInputConfig', +'ImportProductSetsRequest', +'ImportProductSetsResponse', +'InputConfig', +'LatLongRect', +'Likelihood', +'ListProductSetsRequest', +'ListProductSetsResponse', +'ListProductsInProductSetRequest', +'ListProductsInProductSetResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListReferenceImagesRequest', +'ListReferenceImagesResponse', +'LocalizedObjectAnnotation', +'LocationInfo', +'NormalizedVertex', +'OperationMetadata', +'OutputConfig', +'Page', +'Paragraph', +'Position', +'Product', +'ProductSearchClient', +'ProductSearchParams', +'ProductSearchResults', +'ProductSet', +'Property', +'ReferenceImage', +'RemoveProductFromProductSetRequest', +'SafeSearchAnnotation', +'Symbol', +'TextAnnotation', +'TextDetectionParams', +'UpdateProductRequest', +'UpdateProductSetRequest', +'Vertex', +'WebDetection', +'WebDetectionParams', +'Word', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py index c7f40549e472..b1663fdd632d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ImageAnnotatorAsyncClient from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient __all__ = ( - "ImageAnnotatorClient", - "ImageAnnotatorAsyncClient", + 'ImageAnnotatorClient', + 'ImageAnnotatorAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py index 2d7135564480..2dd38756cf68 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from google.cloud.vision_v1p3beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p3beta1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -46,23 +36,19 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore - from google.cloud.vision_v1p3beta1.types import image_annotator - -from .client import ImageAnnotatorClient -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ImageAnnotatorAsyncClient: """Service that performs Google Cloud Vision API detection tasks over client images, such as face, landmark, logo, label, and @@ -83,30 +69,16 @@ class ImageAnnotatorAsyncClient: parse_product_path = staticmethod(ImageAnnotatorClient.parse_product_path) product_set_path = staticmethod(ImageAnnotatorClient.product_set_path) parse_product_set_path = staticmethod(ImageAnnotatorClient.parse_product_set_path) - common_billing_account_path = staticmethod( - ImageAnnotatorClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ImageAnnotatorClient.parse_common_billing_account_path - ) + common_billing_account_path = staticmethod(ImageAnnotatorClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageAnnotatorClient.parse_common_billing_account_path) common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) - parse_common_folder_path = staticmethod( - ImageAnnotatorClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ImageAnnotatorClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ImageAnnotatorClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ImageAnnotatorClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageAnnotatorClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageAnnotatorClient.parse_common_organization_path) common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) - parse_common_project_path = staticmethod( - ImageAnnotatorClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ImageAnnotatorClient.parse_common_project_path) common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) - parse_common_location_path = staticmethod( - ImageAnnotatorClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ImageAnnotatorClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -142,9 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -207,16 +177,12 @@ def universe_domain(self) -> str: get_transport_class = ImageAnnotatorClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator async client. Args: @@ -271,43 +237,31 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p3beta1.ImageAnnotatorAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - async def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + async def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -365,14 +319,10 @@ async def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -386,9 +336,7 @@ async def sample_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -404,19 +352,14 @@ async def sample_batch_annotate_images(): # Done; return the response. return response - async def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be @@ -487,14 +430,10 @@ async def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -508,9 +447,7 @@ async def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.async_batch_annotate_files - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.async_batch_annotate_files] # Validate the universe domain. self._client._validate_universe_domain() @@ -540,13 +477,12 @@ async def __aenter__(self) -> "ImageAnnotatorAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorAsyncClient",) +__all__ = ( + "ImageAnnotatorAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/client.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/client.py index d459e909b674..09ec9b6596c7 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1p3beta1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p3beta1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -63,10 +50,8 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore - from google.cloud.vision_v1p3beta1.types import image_annotator - -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -79,18 +64,14 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] _transport_registry["grpc"] = ImageAnnotatorGrpcTransport _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport _transport_registry["rest"] = ImageAnnotatorRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ImageAnnotatorTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. Args: @@ -166,16 +147,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -214,7 +193,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -231,132 +211,84 @@ def transport(self) -> ImageAnnotatorTransport: return self._transport @staticmethod - def product_path( - project: str, - location: str, - product: str, - ) -> str: + def product_path(project: str,location: str,product: str,) -> str: """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + return "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) @staticmethod - def parse_product_path(path: str) -> Dict[str, str]: + def parse_product_path(path: str) -> Dict[str,str]: """Parses a product path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def product_set_path( - project: str, - location: str, - product_set: str, - ) -> str: + def product_set_path(project: str,location: str,product_set: str,) -> str: """Returns a fully-qualified product_set string.""" - return ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + return "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) @staticmethod - def parse_product_set_path(path: str) -> Dict[str, str]: + def parse_product_set_path(path: str) -> Dict[str,str]: """Parses a product_set path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -388,18 +320,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ImageAnnotatorClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -412,9 +340,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -439,9 +365,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -464,9 +388,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -482,25 +404,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -536,18 +450,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -580,16 +491,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator client. Args: @@ -644,24 +551,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ImageAnnotatorClient._read_environment_variables() - self._client_cert_source = ImageAnnotatorClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ImageAnnotatorClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageAnnotatorClient._read_environment_variables() + self._client_cert_source = ImageAnnotatorClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageAnnotatorClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -672,9 +569,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -683,10 +578,8 @@ def __init__( if transport_provided: # transport is a ImageAnnotatorTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -695,29 +588,20 @@ def __init__( self._transport = cast(ImageAnnotatorTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ImageAnnotatorClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ImageAnnotatorClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport] - ] = ( + transport_init: Union[Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport]] = ( ImageAnnotatorClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ImageAnnotatorTransport], transport) @@ -736,41 +620,28 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p3beta1.ImageAnnotatorClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -828,14 +699,10 @@ def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -864,19 +731,14 @@ def sample_batch_annotate_images(): # Done; return the response. return response - def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be @@ -947,14 +809,10 @@ def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -967,9 +825,7 @@ def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.async_batch_annotate_files - ] + rpc = self._transport._wrapped_methods[self._transport.async_batch_annotate_files] # Validate the universe domain. self._validate_universe_domain() @@ -1007,11 +863,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorClient",) +__all__ = ( + "ImageAnnotatorClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py index 1de28b3fb87a..d3a583db5759 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] -_transport_registry["grpc"] = ImageAnnotatorGrpcTransport -_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport -_transport_registry["rest"] = ImageAnnotatorRestTransport +_transport_registry['grpc'] = ImageAnnotatorGrpcTransport +_transport_registry['grpc_asyncio'] = ImageAnnotatorGrpcAsyncIOTransport +_transport_registry['rest'] = ImageAnnotatorRestTransport __all__ = ( - "ImageAnnotatorTransport", - "ImageAnnotatorGrpcTransport", - "ImageAnnotatorGrpcAsyncIOTransport", - "ImageAnnotatorRestTransport", - "ImageAnnotatorRestInterceptor", + 'ImageAnnotatorTransport', + 'ImageAnnotatorGrpcTransport', + 'ImageAnnotatorGrpcAsyncIOTransport', + 'ImageAnnotatorRestTransport', + 'ImageAnnotatorRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py index 1f027daad808..faa2ee4f3cac 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py @@ -16,22 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1p3beta1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.cloud.vision_v1p3beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,25 +41,24 @@ class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -86,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -96,38 +93,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -158,20 +148,21 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -181,24 +172,21 @@ def operations_client(self): raise NotImplementedError() @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Union[ - image_annotator.BatchAnnotateImagesResponse, - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Union[ + image_annotator.BatchAnnotateImagesResponse, + Awaitable[image_annotator.BatchAnnotateImagesResponse] + ]]: raise NotImplementedError() @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -206,4 +194,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ImageAnnotatorTransport",) +__all__ = ( + 'ImageAnnotatorTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py index 19d16fc5d3a5..4f82d23bf360 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py @@ -16,26 +16,27 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -45,9 +46,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -68,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -79,11 +78,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -98,7 +93,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": client_call_details.method, "response": grpc_response, @@ -123,26 +118,23 @@ class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -266,23 +258,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -318,12 +306,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -343,12 +332,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -364,20 +350,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + operations_pb2.Operation]: r"""Return a callable for the async batch annotate files method over gRPC. Run asynchronous image detection and annotation for a list of @@ -398,15 +382,13 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def close(self): self._logged_channel.close() @@ -416,4 +398,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ImageAnnotatorGrpcTransport",) +__all__ = ( + 'ImageAnnotatorGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py index 73745c486211..2f72327db4b3 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py @@ -15,31 +15,32 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -47,13 +48,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -74,7 +71,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -85,11 +82,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -104,7 +97,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -134,15 +127,13 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -173,26 +164,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -318,9 +307,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -351,12 +338,9 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse]]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -372,21 +356,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations_pb2.Operation], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the async batch annotate files method over gRPC. Run asynchronous image detection and annotation for a list of @@ -407,18 +388,16 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.batch_annotate_images: self._wrap_method( self.batch_annotate_images, @@ -441,7 +420,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -462,4 +442,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) +__all__ = ( + 'ImageAnnotatorGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest.py index 3a71729d0405..d6e3efadf1cb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest.py @@ -13,26 +13,33 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1p3beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -41,7 +48,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -94,15 +100,7 @@ def post_batch_annotate_images(self, response): """ - - def pre_async_batch_annotate_files( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.AsyncBatchAnnotateFilesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnnotateFilesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.AsyncBatchAnnotateFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for async_batch_annotate_files Override in a subclass to manipulate the request or metadata @@ -110,9 +108,7 @@ def pre_async_batch_annotate_files( """ return request, metadata - def post_async_batch_annotate_files( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for async_batch_annotate_files DEPRECATED. Please use the `post_async_batch_annotate_files_with_metadata` @@ -125,11 +121,7 @@ def post_async_batch_annotate_files( """ return response - def post_async_batch_annotate_files_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for async_batch_annotate_files Override in a subclass to read or manipulate the response or metadata after it @@ -144,14 +136,7 @@ def post_async_batch_annotate_files_with_metadata( """ return response, metadata - def pre_batch_annotate_images( - self, - request: image_annotator.BatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -159,9 +144,7 @@ def pre_batch_annotate_images( """ return request, metadata - def post_batch_annotate_images( - self, response: image_annotator.BatchAnnotateImagesResponse - ) -> image_annotator.BatchAnnotateImagesResponse: + def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImagesResponse) -> image_annotator.BatchAnnotateImagesResponse: """Post-rpc interceptor for batch_annotate_images DEPRECATED. Please use the `post_batch_annotate_images_with_metadata` @@ -174,14 +157,7 @@ def post_batch_annotate_images( """ return response - def post_batch_annotate_images_with_metadata( - self, - response: image_annotator.BatchAnnotateImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_images_with_metadata(self, response: image_annotator.BatchAnnotateImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -219,21 +195,20 @@ class ImageAnnotatorRestTransport(_BaseImageAnnotatorRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ImageAnnotatorRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ImageAnnotatorRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -277,11 +252,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -297,28 +271,23 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: """ # 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]]] = {} + http_options: Dict[str, List[Dict[str, str]]] = { + } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1p3beta1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p3beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AsyncBatchAnnotateFiles( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, - ImageAnnotatorRestStub, - ): + class _AsyncBatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateFiles") @@ -330,93 +299,77 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: image_annotator.AsyncBatchAnnotateFilesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the async batch annotate - files method over HTTP. - - Args: - request (~.image_annotator.AsyncBatchAnnotateFilesRequest): - The request object. Multiple async file annotation - requests are batched into a single - service call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + files method over HTTP. + + Args: + request (~.image_annotator.AsyncBatchAnnotateFilesRequest): + The request object. Multiple async file annotation + requests are batched into a single + service call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - request, metadata = self._interceptor.pre_async_batch_annotate_files( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_async_batch_annotate_files(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ImageAnnotatorClient.AsyncBatchAnnotateFiles", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "httpRequest": http_request, @@ -425,17 +378,7 @@ def __call__( ) # Send the request - response = ( - ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -448,24 +391,20 @@ def __call__( resp = self._interceptor.post_async_batch_annotate_files(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ImageAnnotatorClient.async_batch_annotate_files", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "metadata": http_response["headers"], @@ -474,10 +413,7 @@ def __call__( ) return resp - class _BatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -489,29 +425,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Call the batch annotate images method over HTTP. Args: @@ -533,46 +467,32 @@ def __call__( """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ImageAnnotatorClient.BatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "httpRequest": http_request, @@ -581,15 +501,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -604,26 +516,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateImagesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ImageAnnotatorClient.batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "metadata": http_response["headers"], @@ -633,25 +539,20 @@ def __call__( return resp @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + 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._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore + return self._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: # 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._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -661,4 +562,6 @@ def close(self): self._session.close() -__all__ = ("ImageAnnotatorRestTransport",) +__all__=( + 'ImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest_base.py index 16497c3859bd..f8a9283b73cf 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/image_annotator/transports/rest_base.py @@ -14,16 +14,18 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1p3beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -39,16 +41,14 @@ class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -72,9 +72,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -85,31 +83,27 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAsyncBatchAnnotateFiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/files:asyncBatchAnnotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/files:asyncBatchAnnotate', + 'body': '*', + }, ] return http_options @@ -124,23 +118,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -149,24 +137,20 @@ class _BaseBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/images:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/images:annotate', + 'body': '*', + }, ] return http_options @@ -181,26 +165,22 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__ = ("_BaseImageAnnotatorRestTransport",) +__all__=( + '_BaseImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/__init__.py index f2e4fe58e8df..ff3cc167408d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ProductSearchAsyncClient from .client import ProductSearchClient +from .async_client import ProductSearchAsyncClient __all__ = ( - "ProductSearchClient", - "ProductSearchAsyncClient", + 'ProductSearchClient', + 'ProductSearchAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/async_client.py index 5902002a7d3d..bffd9c75d701 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p3beta1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -46,47 +36,45 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p3beta1.services.product_search import pagers +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore - -from google.cloud.vision_v1p3beta1.services.product_search import pagers -from google.cloud.vision_v1p3beta1.types import geometry, product_search_service - -from .client import ProductSearchClient -from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport +from .client import ProductSearchClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ProductSearchAsyncClient: """Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p3beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` """ _client: ProductSearchClient @@ -103,33 +91,17 @@ class ProductSearchAsyncClient: product_set_path = staticmethod(ProductSearchClient.product_set_path) parse_product_set_path = staticmethod(ProductSearchClient.parse_product_set_path) reference_image_path = staticmethod(ProductSearchClient.reference_image_path) - parse_reference_image_path = staticmethod( - ProductSearchClient.parse_reference_image_path - ) - common_billing_account_path = staticmethod( - ProductSearchClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ProductSearchClient.parse_common_billing_account_path - ) + parse_reference_image_path = staticmethod(ProductSearchClient.parse_reference_image_path) + common_billing_account_path = staticmethod(ProductSearchClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductSearchClient.parse_common_billing_account_path) common_folder_path = staticmethod(ProductSearchClient.common_folder_path) - parse_common_folder_path = staticmethod( - ProductSearchClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ProductSearchClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ProductSearchClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ProductSearchClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductSearchClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductSearchClient.parse_common_organization_path) common_project_path = staticmethod(ProductSearchClient.common_project_path) - parse_common_project_path = staticmethod( - ProductSearchClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ProductSearchClient.parse_common_project_path) common_location_path = staticmethod(ProductSearchClient.common_location_path) - parse_common_location_path = staticmethod( - ProductSearchClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ProductSearchClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -165,9 +137,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -230,16 +200,12 @@ def universe_domain(self) -> str: get_transport_class = ProductSearchClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the product search async client. Args: @@ -294,49 +260,39 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p3beta1.ProductSearchAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "credentialsType": None, - }, + } ) - async def create_product_set( - self, - request: Optional[ - Union[product_search_service.CreateProductSetRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product_set: Optional[product_search_service.ProductSet] = None, - product_set_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def create_product_set(self, + request: Optional[Union[product_search_service.CreateProductSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. .. code-block:: python @@ -412,14 +368,10 @@ async def sample_create_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product_set, product_set_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -437,14 +389,14 @@ async def sample_create_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -461,23 +413,20 @@ async def sample_create_product_set(): # Done; return the response. return response - async def list_product_sets( - self, - request: Optional[ - Union[product_search_service.ListProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductSetsAsyncPager: + async def list_product_sets(self, + request: Optional[Union[product_search_service.ListProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductSetsAsyncPager: r"""Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. .. code-block:: python @@ -538,14 +487,10 @@ async def sample_list_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -559,14 +504,14 @@ async def sample_list_product_sets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_product_sets - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_product_sets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -594,22 +539,19 @@ async def sample_list_product_sets(): # Done; return the response. return response - async def get_product_set( - self, - request: Optional[ - Union[product_search_service.GetProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def get_product_set(self, + request: Optional[Union[product_search_service.GetProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -670,14 +612,10 @@ async def sample_get_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -691,14 +629,14 @@ async def sample_get_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -715,27 +653,24 @@ async def sample_get_product_set(): # Done; return the response. return response - async def update_product_set( - self, - request: Optional[ - Union[product_search_service.UpdateProductSetRequest, dict] - ] = None, - *, - product_set: Optional[product_search_service.ProductSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def update_product_set(self, + request: Optional[Union[product_search_service.UpdateProductSetRequest, dict]] = None, + *, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. .. code-block:: python @@ -802,14 +737,10 @@ async def sample_update_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product_set, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -825,16 +756,14 @@ async def sample_update_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.update_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product_set.name", request.product_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product_set.name", request.product_set.name), + )), ) # Validate the universe domain. @@ -851,17 +780,14 @@ async def sample_update_product_set(): # Done; return the response. return response - async def delete_product_set( - self, - request: Optional[ - Union[product_search_service.DeleteProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_product_set(self, + request: Optional[Union[product_search_service.DeleteProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a ProductSet. All Products and ReferenceImages in the ProductSet will be deleted. @@ -870,7 +796,7 @@ async def delete_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -919,14 +845,10 @@ async def sample_delete_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -940,14 +862,14 @@ async def sample_delete_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -961,29 +883,26 @@ async def sample_delete_product_set(): metadata=metadata, ) - async def create_product( - self, - request: Optional[ - Union[product_search_service.CreateProductRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product: Optional[product_search_service.Product] = None, - product_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def create_product(self, + request: Optional[Union[product_search_service.CreateProductRequest, dict]] = None, + *, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. .. code-block:: python @@ -1054,14 +973,10 @@ async def sample_create_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product, product_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1079,14 +994,14 @@ async def sample_create_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1103,23 +1018,20 @@ async def sample_create_product(): # Done; return the response. return response - async def list_products( - self, - request: Optional[ - Union[product_search_service.ListProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsAsyncPager: + async def list_products(self, + request: Optional[Union[product_search_service.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsAsyncPager: r"""Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -1180,14 +1092,10 @@ async def sample_list_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1201,14 +1109,14 @@ async def sample_list_products(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_products - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_products] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1236,20 +1144,19 @@ async def sample_list_products(): # Done; return the response. return response - async def get_product( - self, - request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def get_product(self, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. .. code-block:: python @@ -1305,14 +1212,10 @@ async def sample_get_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1326,14 +1229,14 @@ async def sample_get_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1350,18 +1253,15 @@ async def sample_get_product(): # Done; return the response. return response - async def update_product( - self, - request: Optional[ - Union[product_search_service.UpdateProductRequest, dict] - ] = None, - *, - product: Optional[product_search_service.Product] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def update_product(self, + request: Optional[Union[product_search_service.UpdateProductRequest, dict]] = None, + *, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only display_name, description and labels can be updated right now. @@ -1370,14 +1270,14 @@ async def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. .. code-block:: python @@ -1441,14 +1341,10 @@ async def sample_update_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1464,16 +1360,14 @@ async def sample_update_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.update_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product.name", request.product.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), ) # Validate the universe domain. @@ -1490,17 +1384,14 @@ async def sample_update_product(): # Done; return the response. return response - async def delete_product( - self, - request: Optional[ - Union[product_search_service.DeleteProductRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_product(self, + request: Optional[Union[product_search_service.DeleteProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a product and its reference images. Metadata of the product and all its images will be deleted right @@ -1509,7 +1400,7 @@ async def delete_product( Possible errors: - - Returns NOT_FOUND if the product does not exist. + - Returns NOT_FOUND if the product does not exist. .. code-block:: python @@ -1558,14 +1449,10 @@ async def sample_delete_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1579,14 +1466,14 @@ async def sample_delete_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1600,19 +1487,16 @@ async def sample_delete_product(): metadata=metadata, ) - async def create_reference_image( - self, - request: Optional[ - Union[product_search_service.CreateReferenceImageRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - reference_image: Optional[product_search_service.ReferenceImage] = None, - reference_image_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + async def create_reference_image(self, + request: Optional[Union[product_search_service.CreateReferenceImageRequest, dict]] = None, + *, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is @@ -1627,14 +1511,14 @@ async def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. .. code-block:: python @@ -1715,14 +1599,10 @@ async def sample_create_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, reference_image, reference_image_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1740,14 +1620,14 @@ async def sample_create_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1764,17 +1644,14 @@ async def sample_create_reference_image(): # Done; return the response. return response - async def delete_reference_image( - self, - request: Optional[ - Union[product_search_service.DeleteReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_reference_image(self, + request: Optional[Union[product_search_service.DeleteReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a reference image. The image metadata will be deleted right away, but search @@ -1786,7 +1663,7 @@ async def delete_reference_image( Possible errors: - - Returns NOT_FOUND if the reference image does not exist. + - Returns NOT_FOUND if the reference image does not exist. .. code-block:: python @@ -1837,14 +1714,10 @@ async def sample_delete_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1858,14 +1731,14 @@ async def sample_delete_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1879,24 +1752,21 @@ async def sample_delete_reference_image(): metadata=metadata, ) - async def list_reference_images( - self, - request: Optional[ - Union[product_search_service.ListReferenceImagesRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListReferenceImagesAsyncPager: + async def list_reference_images(self, + request: Optional[Union[product_search_service.ListReferenceImagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListReferenceImagesAsyncPager: r"""Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. .. code-block:: python @@ -1958,14 +1828,10 @@ async def sample_list_reference_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1979,14 +1845,14 @@ async def sample_list_reference_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_reference_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_reference_images] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2014,22 +1880,19 @@ async def sample_list_reference_images(): # Done; return the response. return response - async def get_reference_image( - self, - request: Optional[ - Union[product_search_service.GetReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + async def get_reference_image(self, + request: Optional[Union[product_search_service.GetReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. .. code-block:: python @@ -2089,14 +1952,10 @@ async def sample_get_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2110,14 +1969,14 @@ async def sample_get_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2134,18 +1993,15 @@ async def sample_get_reference_image(): # Done; return the response. return response - async def add_product_to_product_set( - self, - request: Optional[ - Union[product_search_service.AddProductToProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def add_product_to_product_set(self, + request: Optional[Union[product_search_service.AddProductToProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is already present, no change is made. @@ -2153,8 +2009,8 @@ async def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. .. code-block:: python @@ -2216,20 +2072,14 @@ async def sample_add_product_to_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.AddProductToProductSetRequest - ): + if not isinstance(request, product_search_service.AddProductToProductSetRequest): request = product_search_service.AddProductToProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2241,14 +2091,14 @@ async def sample_add_product_to_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.add_product_to_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.add_product_to_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2262,24 +2112,21 @@ async def sample_add_product_to_product_set(): metadata=metadata, ) - async def remove_product_from_product_set( - self, - request: Optional[ - Union[product_search_service.RemoveProductFromProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def remove_product_from_product_set(self, + request: Optional[Union[product_search_service.RemoveProductFromProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Removes a Product from the specified ProductSet. Possible errors: - - Returns NOT_FOUND If the Product is not found under the - ProductSet. + - Returns NOT_FOUND If the Product is not found under the + ProductSet. .. code-block:: python @@ -2341,20 +2188,14 @@ async def sample_remove_product_from_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.RemoveProductFromProductSetRequest - ): + if not isinstance(request, product_search_service.RemoveProductFromProductSetRequest): request = product_search_service.RemoveProductFromProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2366,14 +2207,14 @@ async def sample_remove_product_from_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.remove_product_from_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_product_from_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2387,25 +2228,22 @@ async def sample_remove_product_from_product_set(): metadata=metadata, ) - async def list_products_in_product_set( - self, - request: Optional[ - Union[product_search_service.ListProductsInProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsInProductSetAsyncPager: + async def list_products_in_product_set(self, + request: Optional[Union[product_search_service.ListProductsInProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsInProductSetAsyncPager: r"""Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -2469,20 +2307,14 @@ async def sample_list_products_in_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.ListProductsInProductSetRequest - ): + if not isinstance(request, product_search_service.ListProductsInProductSetRequest): request = product_search_service.ListProductsInProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2492,14 +2324,14 @@ async def sample_list_products_in_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_products_in_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_products_in_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2527,20 +2359,15 @@ async def sample_list_products_in_product_set(): # Done; return the response. return response - async def import_product_sets( - self, - request: Optional[ - Union[product_search_service.ImportProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - input_config: Optional[ - product_search_service.ImportProductSetsInputConfig - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def import_product_sets(self, + request: Optional[Union[product_search_service.ImportProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + input_config: Optional[product_search_service.ImportProductSetsInputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. @@ -2630,14 +2457,10 @@ async def sample_import_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2653,14 +2476,14 @@ async def sample_import_product_sets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.import_product_sets - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.import_product_sets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2691,13 +2514,12 @@ async def __aenter__(self) -> "ProductSearchAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ProductSearchAsyncClient",) +__all__ = ( + "ProductSearchAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/client.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/client.py index 49204ee8fdac..77f866ee7821 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1p3beta1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p3beta1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -63,14 +50,13 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p3beta1.services.product_search import pagers +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore - -from google.cloud.vision_v1p3beta1.services.product_search import pagers -from google.cloud.vision_v1p3beta1.types import geometry, product_search_service - -from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .transports.rest import ProductSearchRestTransport @@ -83,16 +69,14 @@ class ProductSearchClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] _transport_registry["grpc"] = ProductSearchGrpcTransport _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport _transport_registry["rest"] = ProductSearchRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ProductSearchTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProductSearchTransport]: """Returns an appropriate transport class. Args: @@ -115,22 +99,23 @@ class ProductSearchClient(metaclass=ProductSearchClientMeta): """Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p3beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` """ @staticmethod @@ -183,16 +168,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -231,7 +214,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductSearchClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -248,156 +232,95 @@ def transport(self) -> ProductSearchTransport: return self._transport @staticmethod - def product_path( - project: str, - location: str, - product: str, - ) -> str: + def product_path(project: str,location: str,product: str,) -> str: """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + return "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) @staticmethod - def parse_product_path(path: str) -> Dict[str, str]: + def parse_product_path(path: str) -> Dict[str,str]: """Parses a product path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def product_set_path( - project: str, - location: str, - product_set: str, - ) -> str: + def product_set_path(project: str,location: str,product_set: str,) -> str: """Returns a fully-qualified product_set string.""" - return ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + return "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) @staticmethod - def parse_product_set_path(path: str) -> Dict[str, str]: + def parse_product_set_path(path: str) -> Dict[str,str]: """Parses a product_set path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def reference_image_path( - project: str, - location: str, - product: str, - reference_image: str, - ) -> str: + def reference_image_path(project: str,location: str,product: str,reference_image: str,) -> str: """Returns a fully-qualified reference_image string.""" - return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( - project=project, - location=location, - product=product, - reference_image=reference_image, - ) + return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format(project=project, location=location, product=product, reference_image=reference_image, ) @staticmethod - def parse_reference_image_path(path: str) -> Dict[str, str]: + def parse_reference_image_path(path: str) -> Dict[str,str]: """Parses a reference_image path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -429,18 +352,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ProductSearchClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -453,9 +372,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -480,9 +397,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -505,9 +420,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -523,25 +436,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ProductSearchClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ProductSearchClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -577,18 +482,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -621,16 +523,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the product search client. Args: @@ -685,24 +583,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ProductSearchClient._read_environment_variables() - self._client_cert_source = ProductSearchClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ProductSearchClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ProductSearchClient._read_environment_variables() + self._client_cert_source = ProductSearchClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProductSearchClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -713,9 +601,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -724,10 +610,8 @@ def __init__( if transport_provided: # transport is a ProductSearchTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -736,29 +620,20 @@ def __init__( self._transport = cast(ProductSearchTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ProductSearchClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ProductSearchClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ProductSearchTransport], Callable[..., ProductSearchTransport] - ] = ( + transport_init: Union[Type[ProductSearchTransport], Callable[..., ProductSearchTransport]] = ( ProductSearchClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ProductSearchTransport], transport) @@ -777,47 +652,36 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p3beta1.ProductSearchClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "credentialsType": None, - }, + } ) - def create_product_set( - self, - request: Optional[ - Union[product_search_service.CreateProductSetRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product_set: Optional[product_search_service.ProductSet] = None, - product_set_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def create_product_set(self, + request: Optional[Union[product_search_service.CreateProductSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. .. code-block:: python @@ -893,14 +757,10 @@ def sample_create_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product_set, product_set_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -922,7 +782,9 @@ def sample_create_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -939,23 +801,20 @@ def sample_create_product_set(): # Done; return the response. return response - def list_product_sets( - self, - request: Optional[ - Union[product_search_service.ListProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductSetsPager: + def list_product_sets(self, + request: Optional[Union[product_search_service.ListProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductSetsPager: r"""Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. .. code-block:: python @@ -1016,14 +875,10 @@ def sample_list_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1041,7 +896,9 @@ def sample_list_product_sets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1069,22 +926,19 @@ def sample_list_product_sets(): # Done; return the response. return response - def get_product_set( - self, - request: Optional[ - Union[product_search_service.GetProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def get_product_set(self, + request: Optional[Union[product_search_service.GetProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -1145,14 +999,10 @@ def sample_get_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1170,7 +1020,9 @@ def sample_get_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1187,27 +1039,24 @@ def sample_get_product_set(): # Done; return the response. return response - def update_product_set( - self, - request: Optional[ - Union[product_search_service.UpdateProductSetRequest, dict] - ] = None, - *, - product_set: Optional[product_search_service.ProductSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def update_product_set(self, + request: Optional[Union[product_search_service.UpdateProductSetRequest, dict]] = None, + *, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. .. code-block:: python @@ -1274,14 +1123,10 @@ def sample_update_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product_set, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1301,9 +1146,9 @@ def sample_update_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product_set.name", request.product_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product_set.name", request.product_set.name), + )), ) # Validate the universe domain. @@ -1320,17 +1165,14 @@ def sample_update_product_set(): # Done; return the response. return response - def delete_product_set( - self, - request: Optional[ - Union[product_search_service.DeleteProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_product_set(self, + request: Optional[Union[product_search_service.DeleteProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a ProductSet. All Products and ReferenceImages in the ProductSet will be deleted. @@ -1339,7 +1181,7 @@ def delete_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -1388,14 +1230,10 @@ def sample_delete_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1413,7 +1251,9 @@ def sample_delete_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1427,29 +1267,26 @@ def sample_delete_product_set(): metadata=metadata, ) - def create_product( - self, - request: Optional[ - Union[product_search_service.CreateProductRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product: Optional[product_search_service.Product] = None, - product_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def create_product(self, + request: Optional[Union[product_search_service.CreateProductRequest, dict]] = None, + *, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. .. code-block:: python @@ -1520,14 +1357,10 @@ def sample_create_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product, product_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1549,7 +1382,9 @@ def sample_create_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1566,23 +1401,20 @@ def sample_create_product(): # Done; return the response. return response - def list_products( - self, - request: Optional[ - Union[product_search_service.ListProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsPager: + def list_products(self, + request: Optional[Union[product_search_service.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsPager: r"""Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -1643,14 +1475,10 @@ def sample_list_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1668,7 +1496,9 @@ def sample_list_products(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1696,20 +1526,19 @@ def sample_list_products(): # Done; return the response. return response - def get_product( - self, - request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def get_product(self, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. .. code-block:: python @@ -1765,14 +1594,10 @@ def sample_get_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1790,7 +1615,9 @@ def sample_get_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1807,18 +1634,15 @@ def sample_get_product(): # Done; return the response. return response - def update_product( - self, - request: Optional[ - Union[product_search_service.UpdateProductRequest, dict] - ] = None, - *, - product: Optional[product_search_service.Product] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def update_product(self, + request: Optional[Union[product_search_service.UpdateProductRequest, dict]] = None, + *, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only display_name, description and labels can be updated right now. @@ -1827,14 +1651,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. .. code-block:: python @@ -1898,14 +1722,10 @@ def sample_update_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1925,9 +1745,9 @@ def sample_update_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product.name", request.product.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), ) # Validate the universe domain. @@ -1944,17 +1764,14 @@ def sample_update_product(): # Done; return the response. return response - def delete_product( - self, - request: Optional[ - Union[product_search_service.DeleteProductRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_product(self, + request: Optional[Union[product_search_service.DeleteProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a product and its reference images. Metadata of the product and all its images will be deleted right @@ -1963,7 +1780,7 @@ def delete_product( Possible errors: - - Returns NOT_FOUND if the product does not exist. + - Returns NOT_FOUND if the product does not exist. .. code-block:: python @@ -2012,14 +1829,10 @@ def sample_delete_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2037,7 +1850,9 @@ def sample_delete_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2051,19 +1866,16 @@ def sample_delete_product(): metadata=metadata, ) - def create_reference_image( - self, - request: Optional[ - Union[product_search_service.CreateReferenceImageRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - reference_image: Optional[product_search_service.ReferenceImage] = None, - reference_image_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def create_reference_image(self, + request: Optional[Union[product_search_service.CreateReferenceImageRequest, dict]] = None, + *, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is @@ -2078,14 +1890,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. .. code-block:: python @@ -2166,14 +1978,10 @@ def sample_create_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, reference_image, reference_image_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2195,7 +2003,9 @@ def sample_create_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2212,17 +2022,14 @@ def sample_create_reference_image(): # Done; return the response. return response - def delete_reference_image( - self, - request: Optional[ - Union[product_search_service.DeleteReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_reference_image(self, + request: Optional[Union[product_search_service.DeleteReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a reference image. The image metadata will be deleted right away, but search @@ -2234,7 +2041,7 @@ def delete_reference_image( Possible errors: - - Returns NOT_FOUND if the reference image does not exist. + - Returns NOT_FOUND if the reference image does not exist. .. code-block:: python @@ -2285,14 +2092,10 @@ def sample_delete_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2310,7 +2113,9 @@ def sample_delete_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2324,24 +2129,21 @@ def sample_delete_reference_image(): metadata=metadata, ) - def list_reference_images( - self, - request: Optional[ - Union[product_search_service.ListReferenceImagesRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListReferenceImagesPager: + def list_reference_images(self, + request: Optional[Union[product_search_service.ListReferenceImagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListReferenceImagesPager: r"""Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. .. code-block:: python @@ -2403,14 +2205,10 @@ def sample_list_reference_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2428,7 +2226,9 @@ def sample_list_reference_images(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2456,22 +2256,19 @@ def sample_list_reference_images(): # Done; return the response. return response - def get_reference_image( - self, - request: Optional[ - Union[product_search_service.GetReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def get_reference_image(self, + request: Optional[Union[product_search_service.GetReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. .. code-block:: python @@ -2531,14 +2328,10 @@ def sample_get_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2556,7 +2349,9 @@ def sample_get_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2573,18 +2368,15 @@ def sample_get_reference_image(): # Done; return the response. return response - def add_product_to_product_set( - self, - request: Optional[ - Union[product_search_service.AddProductToProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def add_product_to_product_set(self, + request: Optional[Union[product_search_service.AddProductToProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is already present, no change is made. @@ -2592,8 +2384,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. .. code-block:: python @@ -2655,20 +2447,14 @@ def sample_add_product_to_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.AddProductToProductSetRequest - ): + if not isinstance(request, product_search_service.AddProductToProductSetRequest): request = product_search_service.AddProductToProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2679,14 +2465,14 @@ def sample_add_product_to_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.add_product_to_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.add_product_to_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2700,24 +2486,21 @@ def sample_add_product_to_product_set(): metadata=metadata, ) - def remove_product_from_product_set( - self, - request: Optional[ - Union[product_search_service.RemoveProductFromProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def remove_product_from_product_set(self, + request: Optional[Union[product_search_service.RemoveProductFromProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Removes a Product from the specified ProductSet. Possible errors: - - Returns NOT_FOUND If the Product is not found under the - ProductSet. + - Returns NOT_FOUND If the Product is not found under the + ProductSet. .. code-block:: python @@ -2779,20 +2562,14 @@ def sample_remove_product_from_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.RemoveProductFromProductSetRequest - ): + if not isinstance(request, product_search_service.RemoveProductFromProductSetRequest): request = product_search_service.RemoveProductFromProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2803,14 +2580,14 @@ def sample_remove_product_from_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.remove_product_from_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.remove_product_from_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2824,25 +2601,22 @@ def sample_remove_product_from_product_set(): metadata=metadata, ) - def list_products_in_product_set( - self, - request: Optional[ - Union[product_search_service.ListProductsInProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsInProductSetPager: + def list_products_in_product_set(self, + request: Optional[Union[product_search_service.ListProductsInProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsInProductSetPager: r"""Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -2906,20 +2680,14 @@ def sample_list_products_in_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.ListProductsInProductSetRequest - ): + if not isinstance(request, product_search_service.ListProductsInProductSetRequest): request = product_search_service.ListProductsInProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2928,14 +2696,14 @@ def sample_list_products_in_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_products_in_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.list_products_in_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2963,20 +2731,15 @@ def sample_list_products_in_product_set(): # Done; return the response. return response - def import_product_sets( - self, - request: Optional[ - Union[product_search_service.ImportProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - input_config: Optional[ - product_search_service.ImportProductSetsInputConfig - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def import_product_sets(self, + request: Optional[Union[product_search_service.ImportProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + input_config: Optional[product_search_service.ImportProductSetsInputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. @@ -3066,14 +2829,10 @@ def sample_import_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3093,7 +2852,9 @@ def sample_import_product_sets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3132,11 +2893,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ProductSearchClient",) +__all__ = ( + "ProductSearchClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/pagers.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/pagers.py index 4dee59745eaf..5c6237435803 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/pagers.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/pagers.py @@ -13,27 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import ( - Any, - AsyncIterator, - Awaitable, - Callable, - Iterator, - Optional, - Sequence, - Tuple, - Union, -) - from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import retry_async as retries_async - +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[ - retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None - ] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore @@ -58,17 +44,14 @@ class ListProductSetsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductSetsResponse], - request: product_search_service.ListProductSetsRequest, - response: product_search_service.ListProductSetsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductSetsResponse], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -101,12 +84,7 @@ def pages(self) -> Iterator[product_search_service.ListProductSetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.ProductSet]: @@ -114,7 +92,7 @@ def __iter__(self) -> Iterator[product_search_service.ProductSet]: yield from page.product_sets def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductSetsAsyncPager: @@ -134,19 +112,14 @@ class ListProductSetsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListProductSetsResponse] - ], - request: product_search_service.ListProductSetsRequest, - response: product_search_service.ListProductSetsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductSetsResponse]], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -175,20 +148,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListProductSetsResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListProductSetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.ProductSet]: async def async_generator(): async for page in self.pages: @@ -198,7 +163,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsPager: @@ -218,17 +183,14 @@ class ListProductsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductsResponse], - request: product_search_service.ListProductsRequest, - response: product_search_service.ListProductsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductsResponse], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -261,12 +223,7 @@ def pages(self) -> Iterator[product_search_service.ListProductsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.Product]: @@ -274,7 +231,7 @@ def __iter__(self) -> Iterator[product_search_service.Product]: yield from page.products def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsAsyncPager: @@ -294,17 +251,14 @@ class ListProductsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], - request: product_search_service.ListProductsRequest, - response: product_search_service.ListProductsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -337,14 +291,8 @@ async def pages(self) -> AsyncIterator[product_search_service.ListProductsRespon yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.Product]: async def async_generator(): async for page in self.pages: @@ -354,7 +302,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListReferenceImagesPager: @@ -374,17 +322,14 @@ class ListReferenceImagesPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListReferenceImagesResponse], - request: product_search_service.ListReferenceImagesRequest, - response: product_search_service.ListReferenceImagesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListReferenceImagesResponse], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -417,12 +362,7 @@ def pages(self) -> Iterator[product_search_service.ListReferenceImagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.ReferenceImage]: @@ -430,7 +370,7 @@ def __iter__(self) -> Iterator[product_search_service.ReferenceImage]: yield from page.reference_images def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListReferenceImagesAsyncPager: @@ -450,19 +390,14 @@ class ListReferenceImagesAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListReferenceImagesResponse] - ], - request: product_search_service.ListReferenceImagesRequest, - response: product_search_service.ListReferenceImagesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListReferenceImagesResponse]], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -491,20 +426,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListReferenceImagesResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListReferenceImagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.ReferenceImage]: async def async_generator(): async for page in self.pages: @@ -514,7 +441,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsInProductSetPager: @@ -534,17 +461,14 @@ class ListProductsInProductSetPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductsInProductSetResponse], - request: product_search_service.ListProductsInProductSetRequest, - response: product_search_service.ListProductsInProductSetResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductsInProductSetResponse], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -573,18 +497,11 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages( - self, - ) -> Iterator[product_search_service.ListProductsInProductSetResponse]: + def pages(self) -> Iterator[product_search_service.ListProductsInProductSetResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.Product]: @@ -592,7 +509,7 @@ def __iter__(self) -> Iterator[product_search_service.Product]: yield from page.products def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsInProductSetAsyncPager: @@ -612,19 +529,14 @@ class ListProductsInProductSetAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListProductsInProductSetResponse] - ], - request: product_search_service.ListProductsInProductSetRequest, - response: product_search_service.ListProductsInProductSetResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductsInProductSetResponse]], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -653,20 +565,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListProductsInProductSetResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListProductsInProductSetResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.Product]: async def async_generator(): async for page in self.pages: @@ -676,4 +580,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py index e3bd7adc48d8..f5f6aac78c26 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ProductSearchTransport from .grpc import ProductSearchGrpcTransport from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport -from .rest import ProductSearchRestInterceptor, ProductSearchRestTransport +from .rest import ProductSearchRestTransport +from .rest import ProductSearchRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] -_transport_registry["grpc"] = ProductSearchGrpcTransport -_transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport -_transport_registry["rest"] = ProductSearchRestTransport +_transport_registry['grpc'] = ProductSearchGrpcTransport +_transport_registry['grpc_asyncio'] = ProductSearchGrpcAsyncIOTransport +_transport_registry['rest'] = ProductSearchRestTransport __all__ = ( - "ProductSearchTransport", - "ProductSearchGrpcTransport", - "ProductSearchGrpcAsyncIOTransport", - "ProductSearchRestTransport", - "ProductSearchRestInterceptor", + 'ProductSearchTransport', + 'ProductSearchGrpcTransport', + 'ProductSearchGrpcAsyncIOTransport', + 'ProductSearchRestTransport', + 'ProductSearchRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py index dbc3b9149b32..fdb031d4ef7f 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py @@ -16,23 +16,23 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1p3beta1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.protobuf import empty_pb2 # type: ignore -from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.cloud.vision_v1p3beta1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -42,25 +42,24 @@ class ProductSearchTransport(abc.ABC): """Abstract transport class for ProductSearch.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -87,8 +86,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -97,38 +94,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -144,7 +134,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -186,7 +177,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -213,7 +205,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -255,7 +248,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -282,7 +276,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -339,7 +334,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -351,7 +347,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -378,20 +375,21 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -401,198 +399,165 @@ def operations_client(self): raise NotImplementedError() @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - Union[ - product_search_service.ListProductSetsResponse, - Awaitable[product_search_service.ListProductSetsResponse], - ], - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + Union[ + product_search_service.ListProductSetsResponse, + Awaitable[product_search_service.ListProductSetsResponse] + ]]: raise NotImplementedError() @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def delete_product_set( - self, - ) -> Callable[ - [product_search_service.DeleteProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - Union[ - product_search_service.ListProductsResponse, - Awaitable[product_search_service.ListProductsResponse], - ], - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + Union[ + product_search_service.ListProductsResponse, + Awaitable[product_search_service.ListProductsResponse] + ]]: raise NotImplementedError() @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def delete_product( - self, - ) -> Callable[ - [product_search_service.DeleteProductRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - Union[ - product_search_service.ReferenceImage, - Awaitable[product_search_service.ReferenceImage], - ], - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Union[ + product_search_service.ReferenceImage, + Awaitable[product_search_service.ReferenceImage] + ]]: raise NotImplementedError() @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - Union[ - product_search_service.ListReferenceImagesResponse, - Awaitable[product_search_service.ListReferenceImagesResponse], - ], - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Union[ + product_search_service.ListReferenceImagesResponse, + Awaitable[product_search_service.ListReferenceImagesResponse] + ]]: raise NotImplementedError() @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - Union[ - product_search_service.ReferenceImage, - Awaitable[product_search_service.ReferenceImage], - ], - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Union[ + product_search_service.ReferenceImage, + Awaitable[product_search_service.ReferenceImage] + ]]: raise NotImplementedError() @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - Union[ - product_search_service.ListProductsInProductSetResponse, - Awaitable[product_search_service.ListProductsInProductSetResponse], - ], - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Union[ + product_search_service.ListProductsInProductSetResponse, + Awaitable[product_search_service.ListProductsInProductSetResponse] + ]]: raise NotImplementedError() @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -600,4 +565,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ProductSearchTransport",) +__all__ = ( + 'ProductSearchTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py index 4ddca650fe7e..277ad601a4cb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py @@ -16,27 +16,28 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1p3beta1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +47,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +68,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,11 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -99,7 +94,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,22 +110,23 @@ class ProductSearchGrpcTransport(ProductSearchTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p3beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -139,26 +135,23 @@ class ProductSearchGrpcTransport(ProductSearchTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -282,23 +275,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -334,12 +323,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -359,20 +349,17 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - product_search_service.ProductSet, - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the create product set method over gRPC. Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. Returns: Callable[[~.CreateProductSetRequest], @@ -384,29 +371,26 @@ def create_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product_set" not in self._stubs: - self._stubs["create_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet", + if 'create_product_set' not in self._stubs: + self._stubs['create_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet', request_serializer=product_search_service.CreateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["create_product_set"] + return self._stubs['create_product_set'] @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - product_search_service.ListProductSetsResponse, - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse]: r"""Return a callable for the list product sets method over gRPC. Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. Returns: Callable[[~.ListProductSetsRequest], @@ -418,27 +402,25 @@ def list_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_product_sets" not in self._stubs: - self._stubs["list_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets", + if 'list_product_sets' not in self._stubs: + self._stubs['list_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets', request_serializer=product_search_service.ListProductSetsRequest.serialize, response_deserializer=product_search_service.ListProductSetsResponse.deserialize, ) - return self._stubs["list_product_sets"] + return self._stubs['list_product_sets'] @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], product_search_service.ProductSet - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the get product set method over gRPC. Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.GetProductSetRequest], @@ -450,21 +432,18 @@ def get_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product_set" not in self._stubs: - self._stubs["get_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet", + if 'get_product_set' not in self._stubs: + self._stubs['get_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet', request_serializer=product_search_service.GetProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["get_product_set"] + return self._stubs['get_product_set'] @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - product_search_service.ProductSet, - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the update product set method over gRPC. Makes changes to a ProductSet resource. Only display_name can be @@ -472,10 +451,10 @@ def update_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. Returns: Callable[[~.UpdateProductSetRequest], @@ -487,18 +466,18 @@ def update_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product_set" not in self._stubs: - self._stubs["update_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet", + if 'update_product_set' not in self._stubs: + self._stubs['update_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet', request_serializer=product_search_service.UpdateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["update_product_set"] + return self._stubs['update_product_set'] @property - def delete_product_set( - self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. All Products and @@ -509,7 +488,7 @@ def delete_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.DeleteProductSetRequest], @@ -521,32 +500,30 @@ def delete_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product_set" not in self._stubs: - self._stubs["delete_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet", + if 'delete_product_set' not in self._stubs: + self._stubs['delete_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet', request_serializer=product_search_service.DeleteProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product_set"] + return self._stubs['delete_product_set'] @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], product_search_service.Product - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + product_search_service.Product]: r"""Return a callable for the create product method over gRPC. Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. Returns: Callable[[~.CreateProductRequest], @@ -558,29 +535,26 @@ def create_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product" not in self._stubs: - self._stubs["create_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct", + if 'create_product' not in self._stubs: + self._stubs['create_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct', request_serializer=product_search_service.CreateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["create_product"] + return self._stubs['create_product'] @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - product_search_service.ListProductsResponse, - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse]: r"""Return a callable for the list products method over gRPC. Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsRequest], @@ -592,27 +566,25 @@ def list_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products" not in self._stubs: - self._stubs["list_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts", + if 'list_products' not in self._stubs: + self._stubs['list_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts', request_serializer=product_search_service.ListProductsRequest.serialize, response_deserializer=product_search_service.ListProductsResponse.deserialize, ) - return self._stubs["list_products"] + return self._stubs['list_products'] @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], product_search_service.Product - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + product_search_service.Product]: r"""Return a callable for the get product method over gRPC. Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. Returns: Callable[[~.GetProductRequest], @@ -624,20 +596,18 @@ def get_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product" not in self._stubs: - self._stubs["get_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct", + if 'get_product' not in self._stubs: + self._stubs['get_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct', request_serializer=product_search_service.GetProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["get_product"] + return self._stubs['get_product'] @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], product_search_service.Product - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + product_search_service.Product]: r"""Return a callable for the update product method over gRPC. Makes changes to a Product resource. Only display_name, @@ -648,14 +618,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. Returns: Callable[[~.UpdateProductRequest], @@ -667,18 +637,18 @@ def update_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product" not in self._stubs: - self._stubs["update_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct", + if 'update_product' not in self._stubs: + self._stubs['update_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct', request_serializer=product_search_service.UpdateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["update_product"] + return self._stubs['update_product'] @property - def delete_product( - self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + empty_pb2.Empty]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference images. @@ -689,7 +659,7 @@ def delete_product( Possible errors: - - Returns NOT_FOUND if the product does not exist. + - Returns NOT_FOUND if the product does not exist. Returns: Callable[[~.DeleteProductRequest], @@ -701,21 +671,18 @@ def delete_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product" not in self._stubs: - self._stubs["delete_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct", + if 'delete_product' not in self._stubs: + self._stubs['delete_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct', request_serializer=product_search_service.DeleteProductRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product"] + return self._stubs['delete_product'] @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage]: r"""Return a callable for the create reference image method over gRPC. Creates and returns a new ReferenceImage resource. @@ -732,14 +699,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. Returns: Callable[[~.CreateReferenceImageRequest], @@ -751,20 +718,18 @@ def create_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_reference_image" not in self._stubs: - self._stubs["create_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage", + if 'create_reference_image' not in self._stubs: + self._stubs['create_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage', request_serializer=product_search_service.CreateReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["create_reference_image"] + return self._stubs['create_reference_image'] @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + empty_pb2.Empty]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -778,7 +743,7 @@ def delete_reference_image( Possible errors: - - Returns NOT_FOUND if the reference image does not exist. + - Returns NOT_FOUND if the reference image does not exist. Returns: Callable[[~.DeleteReferenceImageRequest], @@ -790,30 +755,27 @@ def delete_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_reference_image" not in self._stubs: - self._stubs["delete_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage", + if 'delete_reference_image' not in self._stubs: + self._stubs['delete_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage', request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_reference_image"] + return self._stubs['delete_reference_image'] @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - product_search_service.ListReferenceImagesResponse, - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse]: r"""Return a callable for the list reference images method over gRPC. Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. Returns: Callable[[~.ListReferenceImagesRequest], @@ -825,28 +787,25 @@ def list_reference_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_reference_images" not in self._stubs: - self._stubs["list_reference_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages", + if 'list_reference_images' not in self._stubs: + self._stubs['list_reference_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages', request_serializer=product_search_service.ListReferenceImagesRequest.serialize, response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, ) - return self._stubs["list_reference_images"] + return self._stubs['list_reference_images'] @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage]: r"""Return a callable for the get reference image method over gRPC. Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. Returns: Callable[[~.GetReferenceImageRequest], @@ -858,20 +817,18 @@ def get_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_reference_image" not in self._stubs: - self._stubs["get_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage", + if 'get_reference_image' not in self._stubs: + self._stubs['get_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage', request_serializer=product_search_service.GetReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["get_reference_image"] + return self._stubs['get_reference_image'] @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], empty_pb2.Empty - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the add product to product set method over gRPC. Adds a Product to the specified ProductSet. If the Product is @@ -881,8 +838,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. Returns: Callable[[~.AddProductToProductSetRequest], @@ -894,22 +851,18 @@ def add_product_to_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "add_product_to_product_set" not in self._stubs: - self._stubs[ - "add_product_to_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet", + if 'add_product_to_product_set' not in self._stubs: + self._stubs['add_product_to_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet', request_serializer=product_search_service.AddProductToProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["add_product_to_product_set"] + return self._stubs['add_product_to_product_set'] @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the remove product from product set method over gRPC. @@ -917,8 +870,8 @@ def remove_product_from_product_set( Possible errors: - - Returns NOT_FOUND If the Product is not found under the - ProductSet. + - Returns NOT_FOUND If the Product is not found under the + ProductSet. Returns: Callable[[~.RemoveProductFromProductSetRequest], @@ -930,23 +883,18 @@ def remove_product_from_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "remove_product_from_product_set" not in self._stubs: - self._stubs[ - "remove_product_from_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet", + if 'remove_product_from_product_set' not in self._stubs: + self._stubs['remove_product_from_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet', request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["remove_product_from_product_set"] + return self._stubs['remove_product_from_product_set'] @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - product_search_service.ListProductsInProductSetResponse, - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse]: r"""Return a callable for the list products in product set method over gRPC. Lists the Products in a ProductSet, in an unspecified order. If @@ -955,8 +903,8 @@ def list_products_in_product_set( Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsInProductSetRequest], @@ -968,22 +916,18 @@ def list_products_in_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products_in_product_set" not in self._stubs: - self._stubs[ - "list_products_in_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet", + if 'list_products_in_product_set' not in self._stubs: + self._stubs['list_products_in_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet', request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, ) - return self._stubs["list_products_in_product_set"] + return self._stubs['list_products_in_product_set'] @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations_pb2.Operation - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + operations_pb2.Operation]: r"""Return a callable for the import product sets method over gRPC. Asynchronous API that imports a list of reference images to @@ -1009,13 +953,13 @@ def import_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_product_sets" not in self._stubs: - self._stubs["import_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets", + if 'import_product_sets' not in self._stubs: + self._stubs['import_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets', request_serializer=product_search_service.ImportProductSetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_product_sets"] + return self._stubs['import_product_sets'] def close(self): self._logged_channel.close() @@ -1025,4 +969,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ProductSearchGrpcTransport",) +__all__ = ( + 'ProductSearchGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py index cc26271ea70d..4a46b4662d45 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py @@ -15,32 +15,33 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1p3beta1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .grpc import ProductSearchGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -48,13 +49,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -75,7 +72,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -86,11 +83,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +98,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -121,22 +114,23 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p3beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -150,15 +144,13 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -189,26 +181,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -334,9 +324,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -367,20 +355,17 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the create product set method over gRPC. Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. Returns: Callable[[~.CreateProductSetRequest], @@ -392,29 +377,26 @@ def create_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product_set" not in self._stubs: - self._stubs["create_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet", + if 'create_product_set' not in self._stubs: + self._stubs['create_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet', request_serializer=product_search_service.CreateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["create_product_set"] + return self._stubs['create_product_set'] @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - Awaitable[product_search_service.ListProductSetsResponse], - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + Awaitable[product_search_service.ListProductSetsResponse]]: r"""Return a callable for the list product sets method over gRPC. Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. Returns: Callable[[~.ListProductSetsRequest], @@ -426,28 +408,25 @@ def list_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_product_sets" not in self._stubs: - self._stubs["list_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets", + if 'list_product_sets' not in self._stubs: + self._stubs['list_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets', request_serializer=product_search_service.ListProductSetsRequest.serialize, response_deserializer=product_search_service.ListProductSetsResponse.deserialize, ) - return self._stubs["list_product_sets"] + return self._stubs['list_product_sets'] @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the get product set method over gRPC. Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.GetProductSetRequest], @@ -459,21 +438,18 @@ def get_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product_set" not in self._stubs: - self._stubs["get_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet", + if 'get_product_set' not in self._stubs: + self._stubs['get_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet', request_serializer=product_search_service.GetProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["get_product_set"] + return self._stubs['get_product_set'] @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the update product set method over gRPC. Makes changes to a ProductSet resource. Only display_name can be @@ -481,10 +457,10 @@ def update_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. Returns: Callable[[~.UpdateProductSetRequest], @@ -496,20 +472,18 @@ def update_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product_set" not in self._stubs: - self._stubs["update_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet", + if 'update_product_set' not in self._stubs: + self._stubs['update_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet', request_serializer=product_search_service.UpdateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["update_product_set"] + return self._stubs['update_product_set'] @property - def delete_product_set( - self, - ) -> Callable[ - [product_search_service.DeleteProductSetRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. All Products and @@ -520,7 +494,7 @@ def delete_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.DeleteProductSetRequest], @@ -532,33 +506,30 @@ def delete_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product_set" not in self._stubs: - self._stubs["delete_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet", + if 'delete_product_set' not in self._stubs: + self._stubs['delete_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet', request_serializer=product_search_service.DeleteProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product_set"] + return self._stubs['delete_product_set'] @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], - Awaitable[product_search_service.Product], - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the create product method over gRPC. Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. Returns: Callable[[~.CreateProductRequest], @@ -570,29 +541,26 @@ def create_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product" not in self._stubs: - self._stubs["create_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct", + if 'create_product' not in self._stubs: + self._stubs['create_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct', request_serializer=product_search_service.CreateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["create_product"] + return self._stubs['create_product'] @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - Awaitable[product_search_service.ListProductsResponse], - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + Awaitable[product_search_service.ListProductsResponse]]: r"""Return a callable for the list products method over gRPC. Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsRequest], @@ -604,28 +572,25 @@ def list_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products" not in self._stubs: - self._stubs["list_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts", + if 'list_products' not in self._stubs: + self._stubs['list_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts', request_serializer=product_search_service.ListProductsRequest.serialize, response_deserializer=product_search_service.ListProductsResponse.deserialize, ) - return self._stubs["list_products"] + return self._stubs['list_products'] @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], - Awaitable[product_search_service.Product], - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the get product method over gRPC. Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. Returns: Callable[[~.GetProductRequest], @@ -637,21 +602,18 @@ def get_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product" not in self._stubs: - self._stubs["get_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct", + if 'get_product' not in self._stubs: + self._stubs['get_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct', request_serializer=product_search_service.GetProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["get_product"] + return self._stubs['get_product'] @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], - Awaitable[product_search_service.Product], - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the update product method over gRPC. Makes changes to a Product resource. Only display_name, @@ -662,14 +624,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. Returns: Callable[[~.UpdateProductRequest], @@ -681,20 +643,18 @@ def update_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product" not in self._stubs: - self._stubs["update_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct", + if 'update_product' not in self._stubs: + self._stubs['update_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct', request_serializer=product_search_service.UpdateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["update_product"] + return self._stubs['update_product'] @property - def delete_product( - self, - ) -> Callable[ - [product_search_service.DeleteProductRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference images. @@ -705,7 +665,7 @@ def delete_product( Possible errors: - - Returns NOT_FOUND if the product does not exist. + - Returns NOT_FOUND if the product does not exist. Returns: Callable[[~.DeleteProductRequest], @@ -717,21 +677,18 @@ def delete_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product" not in self._stubs: - self._stubs["delete_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct", + if 'delete_product' not in self._stubs: + self._stubs['delete_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct', request_serializer=product_search_service.DeleteProductRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product"] + return self._stubs['delete_product'] @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - Awaitable[product_search_service.ReferenceImage], - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage]]: r"""Return a callable for the create reference image method over gRPC. Creates and returns a new ReferenceImage resource. @@ -748,14 +705,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. Returns: Callable[[~.CreateReferenceImageRequest], @@ -767,20 +724,18 @@ def create_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_reference_image" not in self._stubs: - self._stubs["create_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage", + if 'create_reference_image' not in self._stubs: + self._stubs['create_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage', request_serializer=product_search_service.CreateReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["create_reference_image"] + return self._stubs['create_reference_image'] @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -794,7 +749,7 @@ def delete_reference_image( Possible errors: - - Returns NOT_FOUND if the reference image does not exist. + - Returns NOT_FOUND if the reference image does not exist. Returns: Callable[[~.DeleteReferenceImageRequest], @@ -806,30 +761,27 @@ def delete_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_reference_image" not in self._stubs: - self._stubs["delete_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage", + if 'delete_reference_image' not in self._stubs: + self._stubs['delete_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage', request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_reference_image"] + return self._stubs['delete_reference_image'] @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - Awaitable[product_search_service.ListReferenceImagesResponse], - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Awaitable[product_search_service.ListReferenceImagesResponse]]: r"""Return a callable for the list reference images method over gRPC. Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. Returns: Callable[[~.ListReferenceImagesRequest], @@ -841,28 +793,25 @@ def list_reference_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_reference_images" not in self._stubs: - self._stubs["list_reference_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages", + if 'list_reference_images' not in self._stubs: + self._stubs['list_reference_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages', request_serializer=product_search_service.ListReferenceImagesRequest.serialize, response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, ) - return self._stubs["list_reference_images"] + return self._stubs['list_reference_images'] @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - Awaitable[product_search_service.ReferenceImage], - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage]]: r"""Return a callable for the get reference image method over gRPC. Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. Returns: Callable[[~.GetReferenceImageRequest], @@ -874,21 +823,18 @@ def get_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_reference_image" not in self._stubs: - self._stubs["get_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage", + if 'get_reference_image' not in self._stubs: + self._stubs['get_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage', request_serializer=product_search_service.GetReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["get_reference_image"] + return self._stubs['get_reference_image'] @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], - Awaitable[empty_pb2.Empty], - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the add product to product set method over gRPC. Adds a Product to the specified ProductSet. If the Product is @@ -898,8 +844,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. Returns: Callable[[~.AddProductToProductSetRequest], @@ -911,23 +857,18 @@ def add_product_to_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "add_product_to_product_set" not in self._stubs: - self._stubs[ - "add_product_to_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet", + if 'add_product_to_product_set' not in self._stubs: + self._stubs['add_product_to_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet', request_serializer=product_search_service.AddProductToProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["add_product_to_product_set"] + return self._stubs['add_product_to_product_set'] @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], - Awaitable[empty_pb2.Empty], - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the remove product from product set method over gRPC. @@ -935,8 +876,8 @@ def remove_product_from_product_set( Possible errors: - - Returns NOT_FOUND If the Product is not found under the - ProductSet. + - Returns NOT_FOUND If the Product is not found under the + ProductSet. Returns: Callable[[~.RemoveProductFromProductSetRequest], @@ -948,23 +889,18 @@ def remove_product_from_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "remove_product_from_product_set" not in self._stubs: - self._stubs[ - "remove_product_from_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet", + if 'remove_product_from_product_set' not in self._stubs: + self._stubs['remove_product_from_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet', request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["remove_product_from_product_set"] + return self._stubs['remove_product_from_product_set'] @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - Awaitable[product_search_service.ListProductsInProductSetResponse], - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Awaitable[product_search_service.ListProductsInProductSetResponse]]: r"""Return a callable for the list products in product set method over gRPC. Lists the Products in a ProductSet, in an unspecified order. If @@ -973,8 +909,8 @@ def list_products_in_product_set( Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsInProductSetRequest], @@ -986,23 +922,18 @@ def list_products_in_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products_in_product_set" not in self._stubs: - self._stubs[ - "list_products_in_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet", + if 'list_products_in_product_set' not in self._stubs: + self._stubs['list_products_in_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet', request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, ) - return self._stubs["list_products_in_product_set"] + return self._stubs['list_products_in_product_set'] @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], - Awaitable[operations_pb2.Operation], - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import product sets method over gRPC. Asynchronous API that imports a list of reference images to @@ -1028,16 +959,16 @@ def import_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_product_sets" not in self._stubs: - self._stubs["import_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets", + if 'import_product_sets' not in self._stubs: + self._stubs['import_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets', request_serializer=product_search_service.ImportProductSetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_product_sets"] + return self._stubs['import_product_sets'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.create_product_set: self._wrap_method( self.create_product_set, @@ -1045,7 +976,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1087,7 +1019,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1114,7 +1047,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1156,7 +1090,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1183,7 +1118,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1240,7 +1176,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1252,7 +1189,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1279,7 +1217,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1300,4 +1239,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("ProductSearchGrpcAsyncIOTransport",) +__all__ = ( + 'ProductSearchGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest.py index 157314187d5e..bdd00830e0d4 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest.py @@ -13,27 +13,34 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf -from google.protobuf import empty_pb2 # type: ignore + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1p3beta1.types import product_search_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseProductSearchRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,7 +49,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -203,15 +209,7 @@ def post_update_product_set(self, response): """ - - def pre_add_product_to_product_set( - self, - request: product_search_service.AddProductToProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.AddProductToProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_add_product_to_product_set(self, request: product_search_service.AddProductToProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.AddProductToProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for add_product_to_product_set Override in a subclass to manipulate the request or metadata @@ -219,14 +217,7 @@ def pre_add_product_to_product_set( """ return request, metadata - def pre_create_product( - self, - request: product_search_service.CreateProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_product(self, request: product_search_service.CreateProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_product Override in a subclass to manipulate the request or metadata @@ -234,9 +225,7 @@ def pre_create_product( """ return request, metadata - def post_create_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_create_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for create_product DEPRECATED. Please use the `post_create_product_with_metadata` @@ -249,11 +238,7 @@ def post_create_product( """ return response - def post_create_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_product Override in a subclass to read or manipulate the response or metadata after it @@ -268,14 +253,7 @@ def post_create_product_with_metadata( """ return response, metadata - def pre_create_product_set( - self, - request: product_search_service.CreateProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_product_set(self, request: product_search_service.CreateProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_product_set Override in a subclass to manipulate the request or metadata @@ -283,9 +261,7 @@ def pre_create_product_set( """ return request, metadata - def post_create_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_create_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for create_product_set DEPRECATED. Please use the `post_create_product_set_with_metadata` @@ -298,13 +274,7 @@ def post_create_product_set( """ return response - def post_create_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_create_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -319,14 +289,7 @@ def post_create_product_set_with_metadata( """ return response, metadata - def pre_create_reference_image( - self, - request: product_search_service.CreateReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_reference_image(self, request: product_search_service.CreateReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_reference_image Override in a subclass to manipulate the request or metadata @@ -334,9 +297,7 @@ def pre_create_reference_image( """ return request, metadata - def post_create_reference_image( - self, response: product_search_service.ReferenceImage - ) -> product_search_service.ReferenceImage: + def post_create_reference_image(self, response: product_search_service.ReferenceImage) -> product_search_service.ReferenceImage: """Post-rpc interceptor for create_reference_image DEPRECATED. Please use the `post_create_reference_image_with_metadata` @@ -349,13 +310,7 @@ def post_create_reference_image( """ return response - def post_create_reference_image_with_metadata( - self, - response: product_search_service.ReferenceImage, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_create_reference_image_with_metadata(self, response: product_search_service.ReferenceImage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_reference_image Override in a subclass to read or manipulate the response or metadata after it @@ -370,14 +325,7 @@ def post_create_reference_image_with_metadata( """ return response, metadata - def pre_delete_product( - self, - request: product_search_service.DeleteProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_product(self, request: product_search_service.DeleteProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_product Override in a subclass to manipulate the request or metadata @@ -385,14 +333,7 @@ def pre_delete_product( """ return request, metadata - def pre_delete_product_set( - self, - request: product_search_service.DeleteProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_product_set(self, request: product_search_service.DeleteProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_product_set Override in a subclass to manipulate the request or metadata @@ -400,14 +341,7 @@ def pre_delete_product_set( """ return request, metadata - def pre_delete_reference_image( - self, - request: product_search_service.DeleteReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_reference_image(self, request: product_search_service.DeleteReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_reference_image Override in a subclass to manipulate the request or metadata @@ -415,14 +349,7 @@ def pre_delete_reference_image( """ return request, metadata - def pre_get_product( - self, - request: product_search_service.GetProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_product(self, request: product_search_service.GetProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_product Override in a subclass to manipulate the request or metadata @@ -430,9 +357,7 @@ def pre_get_product( """ return request, metadata - def post_get_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_get_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for get_product DEPRECATED. Please use the `post_get_product_with_metadata` @@ -445,11 +370,7 @@ def post_get_product( """ return response - def post_get_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_product Override in a subclass to read or manipulate the response or metadata after it @@ -464,14 +385,7 @@ def post_get_product_with_metadata( """ return response, metadata - def pre_get_product_set( - self, - request: product_search_service.GetProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_product_set(self, request: product_search_service.GetProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_product_set Override in a subclass to manipulate the request or metadata @@ -479,9 +393,7 @@ def pre_get_product_set( """ return request, metadata - def post_get_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_get_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for get_product_set DEPRECATED. Please use the `post_get_product_set_with_metadata` @@ -494,13 +406,7 @@ def post_get_product_set( """ return response - def post_get_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_get_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -515,14 +421,7 @@ def post_get_product_set_with_metadata( """ return response, metadata - def pre_get_reference_image( - self, - request: product_search_service.GetReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_reference_image(self, request: product_search_service.GetReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_reference_image Override in a subclass to manipulate the request or metadata @@ -530,9 +429,7 @@ def pre_get_reference_image( """ return request, metadata - def post_get_reference_image( - self, response: product_search_service.ReferenceImage - ) -> product_search_service.ReferenceImage: + def post_get_reference_image(self, response: product_search_service.ReferenceImage) -> product_search_service.ReferenceImage: """Post-rpc interceptor for get_reference_image DEPRECATED. Please use the `post_get_reference_image_with_metadata` @@ -545,13 +442,7 @@ def post_get_reference_image( """ return response - def post_get_reference_image_with_metadata( - self, - response: product_search_service.ReferenceImage, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_get_reference_image_with_metadata(self, response: product_search_service.ReferenceImage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_reference_image Override in a subclass to read or manipulate the response or metadata after it @@ -566,14 +457,7 @@ def post_get_reference_image_with_metadata( """ return response, metadata - def pre_import_product_sets( - self, - request: product_search_service.ImportProductSetsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ImportProductSetsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_import_product_sets(self, request: product_search_service.ImportProductSetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ImportProductSetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for import_product_sets Override in a subclass to manipulate the request or metadata @@ -581,9 +465,7 @@ def pre_import_product_sets( """ return request, metadata - def post_import_product_sets( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_import_product_sets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for import_product_sets DEPRECATED. Please use the `post_import_product_sets_with_metadata` @@ -596,11 +478,7 @@ def post_import_product_sets( """ return response - def post_import_product_sets_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_import_product_sets_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for import_product_sets Override in a subclass to read or manipulate the response or metadata after it @@ -615,14 +493,7 @@ def post_import_product_sets_with_metadata( """ return response, metadata - def pre_list_products( - self, - request: product_search_service.ListProductsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_products(self, request: product_search_service.ListProductsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_products Override in a subclass to manipulate the request or metadata @@ -630,9 +501,7 @@ def pre_list_products( """ return request, metadata - def post_list_products( - self, response: product_search_service.ListProductsResponse - ) -> product_search_service.ListProductsResponse: + def post_list_products(self, response: product_search_service.ListProductsResponse) -> product_search_service.ListProductsResponse: """Post-rpc interceptor for list_products DEPRECATED. Please use the `post_list_products_with_metadata` @@ -645,14 +514,7 @@ def post_list_products( """ return response - def post_list_products_with_metadata( - self, - response: product_search_service.ListProductsResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_products_with_metadata(self, response: product_search_service.ListProductsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_products Override in a subclass to read or manipulate the response or metadata after it @@ -667,14 +529,7 @@ def post_list_products_with_metadata( """ return response, metadata - def pre_list_product_sets( - self, - request: product_search_service.ListProductSetsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductSetsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_product_sets(self, request: product_search_service.ListProductSetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductSetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_product_sets Override in a subclass to manipulate the request or metadata @@ -682,9 +537,7 @@ def pre_list_product_sets( """ return request, metadata - def post_list_product_sets( - self, response: product_search_service.ListProductSetsResponse - ) -> product_search_service.ListProductSetsResponse: + def post_list_product_sets(self, response: product_search_service.ListProductSetsResponse) -> product_search_service.ListProductSetsResponse: """Post-rpc interceptor for list_product_sets DEPRECATED. Please use the `post_list_product_sets_with_metadata` @@ -697,14 +550,7 @@ def post_list_product_sets( """ return response - def post_list_product_sets_with_metadata( - self, - response: product_search_service.ListProductSetsResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductSetsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_product_sets_with_metadata(self, response: product_search_service.ListProductSetsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductSetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_product_sets Override in a subclass to read or manipulate the response or metadata after it @@ -719,14 +565,7 @@ def post_list_product_sets_with_metadata( """ return response, metadata - def pre_list_products_in_product_set( - self, - request: product_search_service.ListProductsInProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsInProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_products_in_product_set(self, request: product_search_service.ListProductsInProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsInProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_products_in_product_set Override in a subclass to manipulate the request or metadata @@ -734,9 +573,7 @@ def pre_list_products_in_product_set( """ return request, metadata - def post_list_products_in_product_set( - self, response: product_search_service.ListProductsInProductSetResponse - ) -> product_search_service.ListProductsInProductSetResponse: + def post_list_products_in_product_set(self, response: product_search_service.ListProductsInProductSetResponse) -> product_search_service.ListProductsInProductSetResponse: """Post-rpc interceptor for list_products_in_product_set DEPRECATED. Please use the `post_list_products_in_product_set_with_metadata` @@ -749,14 +586,7 @@ def post_list_products_in_product_set( """ return response - def post_list_products_in_product_set_with_metadata( - self, - response: product_search_service.ListProductsInProductSetResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsInProductSetResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_products_in_product_set_with_metadata(self, response: product_search_service.ListProductsInProductSetResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsInProductSetResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_products_in_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -771,14 +601,7 @@ def post_list_products_in_product_set_with_metadata( """ return response, metadata - def pre_list_reference_images( - self, - request: product_search_service.ListReferenceImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListReferenceImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_reference_images(self, request: product_search_service.ListReferenceImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListReferenceImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_reference_images Override in a subclass to manipulate the request or metadata @@ -786,9 +609,7 @@ def pre_list_reference_images( """ return request, metadata - def post_list_reference_images( - self, response: product_search_service.ListReferenceImagesResponse - ) -> product_search_service.ListReferenceImagesResponse: + def post_list_reference_images(self, response: product_search_service.ListReferenceImagesResponse) -> product_search_service.ListReferenceImagesResponse: """Post-rpc interceptor for list_reference_images DEPRECATED. Please use the `post_list_reference_images_with_metadata` @@ -801,14 +622,7 @@ def post_list_reference_images( """ return response - def post_list_reference_images_with_metadata( - self, - response: product_search_service.ListReferenceImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListReferenceImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_reference_images_with_metadata(self, response: product_search_service.ListReferenceImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListReferenceImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_reference_images Override in a subclass to read or manipulate the response or metadata after it @@ -823,14 +637,7 @@ def post_list_reference_images_with_metadata( """ return response, metadata - def pre_remove_product_from_product_set( - self, - request: product_search_service.RemoveProductFromProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.RemoveProductFromProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_remove_product_from_product_set(self, request: product_search_service.RemoveProductFromProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.RemoveProductFromProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for remove_product_from_product_set Override in a subclass to manipulate the request or metadata @@ -838,14 +645,7 @@ def pre_remove_product_from_product_set( """ return request, metadata - def pre_update_product( - self, - request: product_search_service.UpdateProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.UpdateProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_update_product(self, request: product_search_service.UpdateProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.UpdateProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_product Override in a subclass to manipulate the request or metadata @@ -853,9 +653,7 @@ def pre_update_product( """ return request, metadata - def post_update_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_update_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for update_product DEPRECATED. Please use the `post_update_product_with_metadata` @@ -868,11 +666,7 @@ def post_update_product( """ return response - def post_update_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_product Override in a subclass to read or manipulate the response or metadata after it @@ -887,14 +681,7 @@ def post_update_product_with_metadata( """ return response, metadata - def pre_update_product_set( - self, - request: product_search_service.UpdateProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.UpdateProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_update_product_set(self, request: product_search_service.UpdateProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.UpdateProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_product_set Override in a subclass to manipulate the request or metadata @@ -902,9 +689,7 @@ def pre_update_product_set( """ return request, metadata - def post_update_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_update_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for update_product_set DEPRECATED. Please use the `post_update_product_set_with_metadata` @@ -917,13 +702,7 @@ def post_update_product_set( """ return response - def post_update_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_update_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -952,22 +731,23 @@ class ProductSearchRestTransport(_BaseProductSearchRestTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p3beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -976,21 +756,20 @@ class ProductSearchRestTransport(_BaseProductSearchRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ProductSearchRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ProductSearchRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -1034,11 +813,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -1054,28 +832,23 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: """ # 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]]] = {} + http_options: Dict[str, List[Dict[str, str]]] = { + } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1p3beta1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p3beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AddProductToProductSet( - _BaseProductSearchRestTransport._BaseAddProductToProductSet, - ProductSearchRestStub, - ): + class _AddProductToProductSet(_BaseProductSearchRestTransport._BaseAddProductToProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.AddProductToProductSet") @@ -1087,85 +860,69 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.AddProductToProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.AddProductToProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the add product to product - set method over HTTP. - - Args: - request (~.product_search_service.AddProductToProductSetRequest): - The request object. Request message for the ``AddProductToProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + set method over HTTP. + + Args: + request (~.product_search_service.AddProductToProductSetRequest): + The request object. Request message for the ``AddProductToProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_http_options() - request, metadata = self._interceptor.pre_add_product_to_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_add_product_to_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.AddProductToProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "AddProductToProductSet", "httpRequest": http_request, @@ -1174,24 +931,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._AddProductToProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._AddProductToProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _CreateProduct( - _BaseProductSearchRestTransport._BaseCreateProduct, ProductSearchRestStub - ): + class _CreateProduct(_BaseProductSearchRestTransport._BaseCreateProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateProduct") @@ -1203,29 +950,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.CreateProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the create product method over HTTP. Args: @@ -1244,44 +989,32 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateProduct._get_http_options() request, metadata = self._interceptor.pre_create_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateProduct._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateProduct._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateProduct._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.CreateProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "CreateProduct", "httpRequest": http_request, @@ -1290,15 +1023,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1313,24 +1038,20 @@ def __call__( resp = self._interceptor.post_create_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.create_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "CreateProduct", "metadata": http_response["headers"], @@ -1339,9 +1060,7 @@ def __call__( ) return resp - class _CreateProductSet( - _BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub - ): + class _CreateProductSet(_BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateProductSet") @@ -1353,29 +1072,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.CreateProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the create product set method over HTTP. Args: @@ -1399,46 +1116,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateProductSet._get_http_options() - request, metadata = self._interceptor.pre_create_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.CreateProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "CreateProductSet", "httpRequest": http_request, @@ -1447,15 +1150,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1470,26 +1165,20 @@ def __call__( resp = self._interceptor.post_create_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.create_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "CreateProductSet", "metadata": http_response["headers"], @@ -1498,9 +1187,7 @@ def __call__( ) return resp - class _CreateReferenceImage( - _BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub - ): + class _CreateReferenceImage(_BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateReferenceImage") @@ -1512,29 +1199,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def __call__(self, + request: product_search_service.CreateReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ReferenceImage: r"""Call the create reference image method over HTTP. Args: @@ -1555,46 +1240,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_create_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.CreateReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "CreateReferenceImage", "httpRequest": http_request, @@ -1603,15 +1274,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1626,26 +1289,20 @@ def __call__( resp = self._interceptor.post_create_reference_image(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_reference_image_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_reference_image_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ReferenceImage.to_json( - response - ) + response_payload = product_search_service.ReferenceImage.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.create_reference_image", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "CreateReferenceImage", "metadata": http_response["headers"], @@ -1654,9 +1311,7 @@ def __call__( ) return resp - class _DeleteProduct( - _BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub - ): + class _DeleteProduct(_BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProduct") @@ -1668,28 +1323,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete product method over HTTP. Args: @@ -1704,40 +1357,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteProduct._get_http_options() request, metadata = self._interceptor.pre_delete_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProduct._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.DeleteProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "DeleteProduct", "httpRequest": http_request, @@ -1746,23 +1389,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteProductSet( - _BaseProductSearchRestTransport._BaseDeleteProductSet, ProductSearchRestStub - ): + class _DeleteProductSet(_BaseProductSearchRestTransport._BaseDeleteProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProductSet") @@ -1774,28 +1408,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete product set method over HTTP. Args: @@ -1810,42 +1442,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_http_options() - request, metadata = self._interceptor.pre_delete_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_delete_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.DeleteProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "DeleteProductSet", "httpRequest": http_request, @@ -1854,23 +1474,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteReferenceImage( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage, ProductSearchRestStub - ): + class _DeleteReferenceImage(_BaseProductSearchRestTransport._BaseDeleteReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteReferenceImage") @@ -1882,28 +1493,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete reference image method over HTTP. Args: @@ -1918,42 +1527,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_delete_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_delete_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.DeleteReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "DeleteReferenceImage", "httpRequest": http_request, @@ -1962,23 +1559,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetProduct( - _BaseProductSearchRestTransport._BaseGetProduct, ProductSearchRestStub - ): + class _GetProduct(_BaseProductSearchRestTransport._BaseGetProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetProduct") @@ -1990,28 +1578,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.GetProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the get product method over HTTP. Args: @@ -2030,44 +1616,30 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetProduct._get_http_options() request, metadata = self._interceptor.pre_get_product(request, metadata) - transcoded_request = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_transcoded_request( - http_options, request - ) - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetProduct._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_query_params_json( - transcoded_request - ) - ) + query_params = _BaseProductSearchRestTransport._BaseGetProduct._get_query_params_json(transcoded_request) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.GetProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "GetProduct", "httpRequest": http_request, @@ -2076,14 +1648,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2098,24 +1663,20 @@ def __call__( resp = self._interceptor.post_get_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.get_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "GetProduct", "metadata": http_response["headers"], @@ -2124,9 +1685,7 @@ def __call__( ) return resp - class _GetProductSet( - _BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub - ): + class _GetProductSet(_BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetProductSet") @@ -2138,28 +1697,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.GetProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the get product set method over HTTP. Args: @@ -2183,40 +1740,30 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetProductSet._get_http_options() request, metadata = self._interceptor.pre_get_product_set(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseGetProductSet._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.GetProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "GetProductSet", "httpRequest": http_request, @@ -2225,14 +1772,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2247,26 +1787,20 @@ def __call__( resp = self._interceptor.post_get_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.get_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "GetProductSet", "metadata": http_response["headers"], @@ -2275,9 +1809,7 @@ def __call__( ) return resp - class _GetReferenceImage( - _BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub - ): + class _GetReferenceImage(_BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetReferenceImage") @@ -2289,28 +1821,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def __call__(self, + request: product_search_service.GetReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ReferenceImage: r"""Call the get reference image method over HTTP. Args: @@ -2331,42 +1861,30 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_get_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_get_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.GetReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "GetReferenceImage", "httpRequest": http_request, @@ -2375,14 +1893,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2397,26 +1908,20 @@ def __call__( resp = self._interceptor.post_get_reference_image(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_reference_image_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_reference_image_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ReferenceImage.to_json( - response - ) + response_payload = product_search_service.ReferenceImage.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.get_reference_image", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "GetReferenceImage", "metadata": http_response["headers"], @@ -2425,9 +1930,7 @@ def __call__( ) return resp - class _ImportProductSets( - _BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub - ): + class _ImportProductSets(_BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ImportProductSets") @@ -2439,29 +1942,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.ImportProductSetsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: product_search_service.ImportProductSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the import product sets method over HTTP. Args: @@ -2483,46 +1984,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseImportProductSets._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseImportProductSets._get_http_options() - request, metadata = self._interceptor.pre_import_product_sets( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseImportProductSets._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_import_product_sets(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseImportProductSets._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseImportProductSets._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseImportProductSets._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseImportProductSets._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseImportProductSets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.ImportProductSets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ImportProductSets", "httpRequest": http_request, @@ -2531,15 +2018,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ImportProductSets._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._ImportProductSets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2552,24 +2031,20 @@ def __call__( resp = self._interceptor.post_import_product_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_import_product_sets_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_import_product_sets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.import_product_sets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ImportProductSets", "metadata": http_response["headers"], @@ -2578,9 +2053,7 @@ def __call__( ) return resp - class _ListProducts( - _BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub - ): + class _ListProducts(_BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProducts") @@ -2592,28 +2065,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductsResponse: + def __call__(self, + request: product_search_service.ListProductsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductsResponse: r"""Call the list products method over HTTP. Args: @@ -2632,40 +2103,30 @@ def __call__( Response message for the ``ListProducts`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProducts._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProducts._get_http_options() request, metadata = self._interceptor.pre_list_products(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseListProducts._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseListProducts._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProducts._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProducts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.ListProducts", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListProducts", "httpRequest": http_request, @@ -2674,14 +2135,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListProducts._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2696,26 +2150,20 @@ def __call__( resp = self._interceptor.post_list_products(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_products_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_products_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductsResponse.to_json(response) - ) + response_payload = product_search_service.ListProductsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.list_products", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListProducts", "metadata": http_response["headers"], @@ -2724,9 +2172,7 @@ def __call__( ) return resp - class _ListProductSets( - _BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub - ): + class _ListProductSets(_BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProductSets") @@ -2738,28 +2184,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductSetsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductSetsResponse: + def __call__(self, + request: product_search_service.ListProductSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductSetsResponse: r"""Call the list product sets method over HTTP. Args: @@ -2778,42 +2222,30 @@ def __call__( Response message for the ``ListProductSets`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProductSets._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProductSets._get_http_options() - request, metadata = self._interceptor.pre_list_product_sets( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListProductSets._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_product_sets(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListProductSets._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProductSets._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProductSets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.ListProductSets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListProductSets", "httpRequest": http_request, @@ -2822,14 +2254,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListProductSets._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListProductSets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2844,26 +2269,20 @@ def __call__( resp = self._interceptor.post_list_product_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_product_sets_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_product_sets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductSetsResponse.to_json(response) - ) + response_payload = product_search_service.ListProductSetsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.list_product_sets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListProductSets", "metadata": http_response["headers"], @@ -2872,10 +2291,7 @@ def __call__( ) return resp - class _ListProductsInProductSet( - _BaseProductSearchRestTransport._BaseListProductsInProductSet, - ProductSearchRestStub, - ): + class _ListProductsInProductSet(_BaseProductSearchRestTransport._BaseListProductsInProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProductsInProductSet") @@ -2887,86 +2303,72 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductsInProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductsInProductSetResponse: + def __call__(self, + request: product_search_service.ListProductsInProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductsInProductSetResponse: r"""Call the list products in product - set method over HTTP. - - Args: - request (~.product_search_service.ListProductsInProductSetRequest): - The request object. Request message for the ``ListProductsInProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.product_search_service.ListProductsInProductSetResponse: - Response message for the ``ListProductsInProductSet`` - method. + set method over HTTP. + + Args: + request (~.product_search_service.ListProductsInProductSetRequest): + The request object. Request message for the ``ListProductsInProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.product_search_service.ListProductsInProductSetResponse: + Response message for the ``ListProductsInProductSet`` + method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_http_options() - request, metadata = self._interceptor.pre_list_products_in_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_products_in_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.ListProductsInProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListProductsInProductSet", "httpRequest": http_request, @@ -2975,16 +2377,7 @@ def __call__( ) # Send the request - response = ( - ProductSearchRestTransport._ListProductsInProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - ) + response = ProductSearchRestTransport._ListProductsInProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2999,28 +2392,20 @@ def __call__( resp = self._interceptor.post_list_products_in_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_products_in_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_products_in_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductsInProductSetResponse.to_json( - response - ) - ) + response_payload = product_search_service.ListProductsInProductSetResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.list_products_in_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListProductsInProductSet", "metadata": http_response["headers"], @@ -3029,9 +2414,7 @@ def __call__( ) return resp - class _ListReferenceImages( - _BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub - ): + class _ListReferenceImages(_BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListReferenceImages") @@ -3043,28 +2426,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListReferenceImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListReferenceImagesResponse: + def __call__(self, + request: product_search_service.ListReferenceImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListReferenceImagesResponse: r"""Call the list reference images method over HTTP. Args: @@ -3083,42 +2464,30 @@ def __call__( Response message for the ``ListReferenceImages`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListReferenceImages._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListReferenceImages._get_http_options() - request, metadata = self._interceptor.pre_list_reference_images( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListReferenceImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_reference_images(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListReferenceImages._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListReferenceImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListReferenceImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.ListReferenceImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListReferenceImages", "httpRequest": http_request, @@ -3127,14 +2496,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListReferenceImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListReferenceImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3149,28 +2511,20 @@ def __call__( resp = self._interceptor.post_list_reference_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_reference_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_reference_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListReferenceImagesResponse.to_json( - response - ) - ) + response_payload = product_search_service.ListReferenceImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.list_reference_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "ListReferenceImages", "metadata": http_response["headers"], @@ -3179,10 +2533,7 @@ def __call__( ) return resp - class _RemoveProductFromProductSet( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, - ProductSearchRestStub, - ): + class _RemoveProductFromProductSet(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.RemoveProductFromProductSet") @@ -3194,85 +2545,69 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.RemoveProductFromProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.RemoveProductFromProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the remove product from - product set method over HTTP. - - Args: - request (~.product_search_service.RemoveProductFromProductSetRequest): - The request object. Request message for the ``RemoveProductFromProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + product set method over HTTP. + + Args: + request (~.product_search_service.RemoveProductFromProductSetRequest): + The request object. Request message for the ``RemoveProductFromProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_http_options() - request, metadata = self._interceptor.pre_remove_product_from_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_remove_product_from_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.RemoveProductFromProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "RemoveProductFromProductSet", "httpRequest": http_request, @@ -3281,26 +2616,14 @@ def __call__( ) # Send the request - response = ( - ProductSearchRestTransport._RemoveProductFromProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ProductSearchRestTransport._RemoveProductFromProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _UpdateProduct( - _BaseProductSearchRestTransport._BaseUpdateProduct, ProductSearchRestStub - ): + class _UpdateProduct(_BaseProductSearchRestTransport._BaseUpdateProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProduct") @@ -3312,29 +2635,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.UpdateProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.UpdateProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the update product method over HTTP. Args: @@ -3353,44 +2674,32 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseUpdateProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseUpdateProduct._get_http_options() request, metadata = self._interceptor.pre_update_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProduct._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseUpdateProduct._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseUpdateProduct._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseUpdateProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseUpdateProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.UpdateProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "UpdateProduct", "httpRequest": http_request, @@ -3399,15 +2708,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._UpdateProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._UpdateProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3422,24 +2723,20 @@ def __call__( resp = self._interceptor.post_update_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_update_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.update_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "UpdateProduct", "metadata": http_response["headers"], @@ -3448,9 +2745,7 @@ def __call__( ) return resp - class _UpdateProductSet( - _BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub - ): + class _UpdateProductSet(_BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProductSet") @@ -3462,29 +2757,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.UpdateProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.UpdateProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the update product set method over HTTP. Args: @@ -3508,46 +2801,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseUpdateProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_http_options() - request, metadata = self._interceptor.pre_update_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p3beta1.ProductSearchClient.UpdateProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "UpdateProductSet", "httpRequest": http_request, @@ -3556,15 +2835,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._UpdateProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._UpdateProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3579,26 +2850,20 @@ def __call__( resp = self._interceptor.post_update_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_update_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p3beta1.ProductSearchClient.update_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p3beta1.ProductSearch", "rpcName": "UpdateProductSet", "metadata": http_response["headers"], @@ -3608,188 +2873,148 @@ def __call__( return resp @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], empty_pb2.Empty - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AddProductToProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._AddProductToProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], product_search_service.Product - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + product_search_service.Product]: # 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._CreateProduct(self._session, self._host, self._interceptor) # type: ignore + return self._CreateProduct(self._session, self._host, self._interceptor) # type: ignore @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - product_search_service.ProductSet, - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet]: # 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._CreateProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._CreateProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage]: # 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._CreateReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._CreateReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def delete_product( - self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteProduct(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteProduct(self._session, self._host, self._interceptor) # type: ignore @property - def delete_product_set( - self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], product_search_service.Product - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + product_search_service.Product]: # 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._GetProduct(self._session, self._host, self._interceptor) # type: ignore + return self._GetProduct(self._session, self._host, self._interceptor) # type: ignore @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], product_search_service.ProductSet - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + product_search_service.ProductSet]: # 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._GetProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._GetProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage]: # 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._GetReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._GetReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations_pb2.Operation - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + 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._ImportProductSets(self._session, self._host, self._interceptor) # type: ignore + return self._ImportProductSets(self._session, self._host, self._interceptor) # type: ignore @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - product_search_service.ListProductsResponse, - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse]: # 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._ListProducts(self._session, self._host, self._interceptor) # type: ignore + return self._ListProducts(self._session, self._host, self._interceptor) # type: ignore @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - product_search_service.ListProductSetsResponse, - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse]: # 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._ListProductSets(self._session, self._host, self._interceptor) # type: ignore + return self._ListProductSets(self._session, self._host, self._interceptor) # type: ignore @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - product_search_service.ListProductsInProductSetResponse, - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse]: # 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._ListProductsInProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._ListProductsInProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - product_search_service.ListReferenceImagesResponse, - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse]: # 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._ListReferenceImages(self._session, self._host, self._interceptor) # type: ignore + return self._ListReferenceImages(self._session, self._host, self._interceptor) # type: ignore @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._RemoveProductFromProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._RemoveProductFromProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], product_search_service.Product - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + product_search_service.Product]: # 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._UpdateProduct(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateProduct(self._session, self._host, self._interceptor) # type: ignore @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - product_search_service.ProductSet, - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet]: # 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._UpdateProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateProductSet(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -3799,4 +3024,6 @@ def close(self): self._session.close() -__all__ = ("ProductSearchRestTransport",) +__all__=( + 'ProductSearchRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest_base.py index b29be1fe56d3..9ebf408586b5 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/services/product_search/transports/rest_base.py @@ -14,17 +14,19 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1p3beta1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore class _BaseProductSearchRestTransport(ProductSearchTransport): @@ -40,16 +42,14 @@ class _BaseProductSearchRestTransport(ProductSearchTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -73,9 +73,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -86,39 +84,33 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAddProductToProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct', + 'body': '*', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.AddProductToProductSetRequest.pb( - request - ) + pb_request = product_search_service.AddProductToProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -127,23 +119,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseAddProductToProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -152,24 +138,20 @@ class _BaseCreateProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/{parent=projects/*/locations/*}/products", - "body": "product", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*}/products', + 'body': 'product', + }, ] return http_options @@ -184,23 +166,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -209,24 +185,20 @@ class _BaseCreateProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/{parent=projects/*/locations/*}/productSets", - "body": "product_set", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*}/productSets', + 'body': 'product_set', + }, ] return http_options @@ -241,23 +213,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -266,24 +232,20 @@ class _BaseCreateReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages", - "body": "reference_image", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages', + 'body': 'reference_image', + }, ] return http_options @@ -298,23 +260,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -323,23 +279,19 @@ class _BaseDeleteProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1p3beta1/{name=projects/*/locations/*/products/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/products/*}', + }, ] return http_options @@ -351,17 +303,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -370,23 +316,19 @@ class _BaseDeleteProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1p3beta1/{name=projects/*/locations/*/productSets/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/productSets/*}', + }, ] return http_options @@ -398,17 +340,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -417,23 +353,19 @@ class _BaseDeleteReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}', + }, ] return http_options @@ -445,17 +377,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -464,23 +390,19 @@ class _BaseGetProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{name=projects/*/locations/*/products/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/products/*}', + }, ] return http_options @@ -492,17 +414,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -511,23 +427,19 @@ class _BaseGetProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{name=projects/*/locations/*/productSets/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/productSets/*}', + }, ] return http_options @@ -539,17 +451,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -558,23 +464,19 @@ class _BaseGetReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}', + }, ] return http_options @@ -586,17 +488,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -605,24 +501,20 @@ class _BaseImportProductSets: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/{parent=projects/*/locations/*}/productSets:import", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*}/productSets:import', + 'body': '*', + }, ] return http_options @@ -637,23 +529,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseImportProductSets._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseImportProductSets._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -662,23 +548,19 @@ class _BaseListProducts: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{parent=projects/*/locations/*}/products", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*}/products', + }, ] return http_options @@ -690,17 +572,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProducts._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProducts._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -709,23 +585,19 @@ class _BaseListProductSets: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{parent=projects/*/locations/*}/productSets", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*}/productSets', + }, ] return http_options @@ -737,17 +609,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProductSets._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProductSets._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -756,47 +622,35 @@ class _BaseListProductsInProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.ListProductsInProductSetRequest.pb( - request - ) + pb_request = product_search_service.ListProductsInProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProductsInProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -805,23 +659,19 @@ class _BaseListReferenceImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages', + }, ] return http_options @@ -833,17 +683,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListReferenceImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListReferenceImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -852,32 +696,26 @@ class _BaseRemoveProductFromProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct', + 'body': '*', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.RemoveProductFromProductSetRequest.pb( - request - ) + pb_request = product_search_service.RemoveProductFromProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -886,23 +724,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -911,24 +743,20 @@ class _BaseUpdateProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1p3beta1/{product.name=projects/*/locations/*/products/*}", - "body": "product", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p3beta1/{product.name=projects/*/locations/*/products/*}', + 'body': 'product', + }, ] return http_options @@ -943,23 +771,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseUpdateProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseUpdateProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -968,24 +790,20 @@ class _BaseUpdateProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}", - "body": "product_set", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}', + 'body': 'product_set', + }, ] return http_options @@ -1000,26 +818,22 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseUpdateProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseUpdateProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__ = ("_BaseProductSearchRestTransport",) +__all__=( + '_BaseProductSearchRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/__init__.py index e5688e0c64f2..652b20e0e18c 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/__init__.py @@ -13,7 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .geometry import BoundingPoly, NormalizedVertex, Position, Vertex +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Position, + Vertex, +) from .image_annotator import ( AnnotateFileResponse, AnnotateImageRequest, @@ -41,7 +46,6 @@ ImageSource, InputConfig, LatLongRect, - Likelihood, LocalizedObjectAnnotation, LocationInfo, OperationMetadata, @@ -50,8 +54,12 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, + Likelihood, +) +from .product_search import ( + ProductSearchParams, + ProductSearchResults, ) -from .product_search import ProductSearchParams, ProductSearchResults from .product_search_service import ( AddProductToProductSetRequest, BatchOperationMetadata, @@ -83,85 +91,94 @@ UpdateProductRequest, UpdateProductSetRequest, ) -from .text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word -from .web_detection import WebDetection +from .text_annotation import ( + Block, + Page, + Paragraph, + Symbol, + TextAnnotation, + Word, +) +from .web_detection import ( + WebDetection, +) __all__ = ( - "BoundingPoly", - "NormalizedVertex", - "Position", - "Vertex", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "Image", - "ImageAnnotationContext", - "ImageContext", - "ImageProperties", - "ImageSource", - "InputConfig", - "LatLongRect", - "LocalizedObjectAnnotation", - "LocationInfo", - "OperationMetadata", - "OutputConfig", - "Property", - "SafeSearchAnnotation", - "TextDetectionParams", - "WebDetectionParams", - "Likelihood", - "ProductSearchParams", - "ProductSearchResults", - "AddProductToProductSetRequest", - "BatchOperationMetadata", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "Product", - "ProductSet", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Block", - "Page", - "Paragraph", - "Symbol", - "TextAnnotation", - "Word", - "WebDetection", + 'BoundingPoly', + 'NormalizedVertex', + 'Position', + 'Vertex', + 'AnnotateFileResponse', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'ColorInfo', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'DominantColorsAnnotation', + 'EntityAnnotation', + 'FaceAnnotation', + 'Feature', + 'GcsDestination', + 'GcsSource', + 'Image', + 'ImageAnnotationContext', + 'ImageContext', + 'ImageProperties', + 'ImageSource', + 'InputConfig', + 'LatLongRect', + 'LocalizedObjectAnnotation', + 'LocationInfo', + 'OperationMetadata', + 'OutputConfig', + 'Property', + 'SafeSearchAnnotation', + 'TextDetectionParams', + 'WebDetectionParams', + 'Likelihood', + 'ProductSearchParams', + 'ProductSearchResults', + 'AddProductToProductSetRequest', + 'BatchOperationMetadata', + 'CreateProductRequest', + 'CreateProductSetRequest', + 'CreateReferenceImageRequest', + 'DeleteProductRequest', + 'DeleteProductSetRequest', + 'DeleteReferenceImageRequest', + 'GetProductRequest', + 'GetProductSetRequest', + 'GetReferenceImageRequest', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ListProductsRequest', + 'ListProductsResponse', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'Product', + 'ProductSet', + 'ReferenceImage', + 'RemoveProductFromProductSetRequest', + 'UpdateProductRequest', + 'UpdateProductSetRequest', + 'Block', + 'Page', + 'Paragraph', + 'Symbol', + 'TextAnnotation', + 'Word', + 'WebDetection', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/geometry.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/geometry.py index d885e4d5e3c2..d7e647bb32d1 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/geometry.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/geometry.py @@ -19,13 +19,14 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p3beta1", + package='google.cloud.vision.v1p3beta1', manifest={ - "Vertex", - "NormalizedVertex", - "BoundingPoly", - "Position", + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + 'Position', }, ) @@ -84,15 +85,15 @@ class BoundingPoly(proto.Message): The bounding polygon normalized vertices. """ - vertices: MutableSequence["Vertex"] = proto.RepeatedField( + vertices: MutableSequence['Vertex'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Vertex", + message='Vertex', ) - normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="NormalizedVertex", + message='NormalizedVertex', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/image_annotator.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/image_annotator.py index d9726c6461f3..71eb551fe9f9 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/image_annotator.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/image_annotator.py @@ -17,57 +17,56 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search +from google.cloud.vision_v1p3beta1.types import text_annotation +from google.cloud.vision_v1p3beta1.types import web_detection as gcv_web_detection from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.type import color_pb2 # type: ignore from google.type import latlng_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1p3beta1.types import ( - geometry, - product_search, - text_annotation, -) -from google.cloud.vision_v1p3beta1.types import web_detection as gcv_web_detection __protobuf__ = proto.module( - package="google.cloud.vision.v1p3beta1", + package='google.cloud.vision.v1p3beta1', manifest={ - "Likelihood", - "Feature", - "ImageSource", - "Image", - "FaceAnnotation", - "LocationInfo", - "Property", - "EntityAnnotation", - "LocalizedObjectAnnotation", - "SafeSearchAnnotation", - "LatLongRect", - "ColorInfo", - "DominantColorsAnnotation", - "ImageProperties", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "WebDetectionParams", - "TextDetectionParams", - "ImageContext", - "AnnotateImageRequest", - "ImageAnnotationContext", - "AnnotateImageResponse", - "AnnotateFileResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "InputConfig", - "OutputConfig", - "GcsSource", - "GcsDestination", - "OperationMetadata", + 'Likelihood', + 'Feature', + 'ImageSource', + 'Image', + 'FaceAnnotation', + 'LocationInfo', + 'Property', + 'EntityAnnotation', + 'LocalizedObjectAnnotation', + 'SafeSearchAnnotation', + 'LatLongRect', + 'ColorInfo', + 'DominantColorsAnnotation', + 'ImageProperties', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'WebDetectionParams', + 'TextDetectionParams', + 'ImageContext', + 'AnnotateImageRequest', + 'ImageAnnotationContext', + 'AnnotateImageResponse', + 'AnnotateFileResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + 'OperationMetadata', }, ) @@ -122,7 +121,6 @@ class Feature(proto.Message): ``TEXT_DETECTION`` also support "builtin/weekly" for the bleeding edge release updated weekly. """ - class Type(proto.Enum): r"""Type of Google Cloud Vision API feature to be extracted. @@ -254,10 +252,10 @@ class Image(proto.Message): proto.BYTES, number=1, ) - source: "ImageSource" = proto.Field( + source: 'ImageSource' = proto.Field( proto.MESSAGE, number=2, - message="ImageSource", + message='ImageSource', ) @@ -327,7 +325,6 @@ class Landmark(proto.Message): position (google.cloud.vision_v1p3beta1.types.Position): Face landmark position. """ - class Type(proto.Enum): r"""Face landmark (feature) type. Left and right are defined from the vantage of the viewer of the image without considering mirror @@ -443,10 +440,10 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_: "FaceAnnotation.Landmark.Type" = proto.Field( + type_: 'FaceAnnotation.Landmark.Type' = proto.Field( proto.ENUM, number=3, - enum="FaceAnnotation.Landmark.Type", + enum='FaceAnnotation.Landmark.Type', ) position: geometry.Position = proto.Field( proto.MESSAGE, @@ -489,40 +486,40 @@ class Type(proto.Enum): proto.FLOAT, number=8, ) - joy_likelihood: "Likelihood" = proto.Field( + joy_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) - sorrow_likelihood: "Likelihood" = proto.Field( + sorrow_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=10, - enum="Likelihood", + enum='Likelihood', ) - anger_likelihood: "Likelihood" = proto.Field( + anger_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=11, - enum="Likelihood", + enum='Likelihood', ) - surprise_likelihood: "Likelihood" = proto.Field( + surprise_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=12, - enum="Likelihood", + enum='Likelihood', ) - under_exposed_likelihood: "Likelihood" = proto.Field( + under_exposed_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=13, - enum="Likelihood", + enum='Likelihood', ) - blurred_likelihood: "Likelihood" = proto.Field( + blurred_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=14, - enum="Likelihood", + enum='Likelihood', ) - headwear_likelihood: "Likelihood" = proto.Field( + headwear_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=15, - enum="Likelihood", + enum='Likelihood', ) @@ -641,15 +638,15 @@ class EntityAnnotation(proto.Message): number=7, message=geometry.BoundingPoly, ) - locations: MutableSequence["LocationInfo"] = proto.RepeatedField( + locations: MutableSequence['LocationInfo'] = proto.RepeatedField( proto.MESSAGE, number=8, - message="LocationInfo", + message='LocationInfo', ) - properties: MutableSequence["Property"] = proto.RepeatedField( + properties: MutableSequence['Property'] = proto.RepeatedField( proto.MESSAGE, number=9, - message="Property", + message='Property', ) @@ -725,30 +722,30 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult: "Likelihood" = proto.Field( + adult: 'Likelihood' = proto.Field( proto.ENUM, number=1, - enum="Likelihood", + enum='Likelihood', ) - spoof: "Likelihood" = proto.Field( + spoof: 'Likelihood' = proto.Field( proto.ENUM, number=2, - enum="Likelihood", + enum='Likelihood', ) - medical: "Likelihood" = proto.Field( + medical: 'Likelihood' = proto.Field( proto.ENUM, number=3, - enum="Likelihood", + enum='Likelihood', ) - violence: "Likelihood" = proto.Field( + violence: 'Likelihood' = proto.Field( proto.ENUM, number=4, - enum="Likelihood", + enum='Likelihood', ) - racy: "Likelihood" = proto.Field( + racy: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) @@ -812,10 +809,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence["ColorInfo"] = proto.RepeatedField( + colors: MutableSequence['ColorInfo'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ColorInfo", + message='ColorInfo', ) @@ -828,10 +825,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: "DominantColorsAnnotation" = proto.Field( + dominant_colors: 'DominantColorsAnnotation' = proto.Field( proto.MESSAGE, number=1, - message="DominantColorsAnnotation", + message='DominantColorsAnnotation', ) @@ -875,10 +872,10 @@ class CropHintsAnnotation(proto.Message): Crop hint results. """ - crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( + crop_hints: MutableSequence['CropHint'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="CropHint", + message='CropHint', ) @@ -970,34 +967,34 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect: "LatLongRect" = proto.Field( + lat_long_rect: 'LatLongRect' = proto.Field( proto.MESSAGE, number=1, - message="LatLongRect", + message='LatLongRect', ) language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params: "CropHintsParams" = proto.Field( + crop_hints_params: 'CropHintsParams' = proto.Field( proto.MESSAGE, number=4, - message="CropHintsParams", + message='CropHintsParams', ) product_search_params: product_search.ProductSearchParams = proto.Field( proto.MESSAGE, number=5, message=product_search.ProductSearchParams, ) - web_detection_params: "WebDetectionParams" = proto.Field( + web_detection_params: 'WebDetectionParams' = proto.Field( proto.MESSAGE, number=6, - message="WebDetectionParams", + message='WebDetectionParams', ) - text_detection_params: "TextDetectionParams" = proto.Field( + text_detection_params: 'TextDetectionParams' = proto.Field( proto.MESSAGE, number=12, - message="TextDetectionParams", + message='TextDetectionParams', ) @@ -1015,20 +1012,20 @@ class AnnotateImageRequest(proto.Message): image. """ - image: "Image" = proto.Field( + image: 'Image' = proto.Field( proto.MESSAGE, number=1, - message="Image", + message='Image', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) @@ -1108,57 +1105,55 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( + face_annotations: MutableSequence['FaceAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="FaceAnnotation", + message='FaceAnnotation', ) - landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + landmark_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="EntityAnnotation", + message='EntityAnnotation', ) - logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + logo_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="EntityAnnotation", + message='EntityAnnotation', ) - label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + label_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="EntityAnnotation", + message='EntityAnnotation', ) - localized_object_annotations: MutableSequence[ - "LocalizedObjectAnnotation" - ] = proto.RepeatedField( + localized_object_annotations: MutableSequence['LocalizedObjectAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=22, - message="LocalizedObjectAnnotation", + message='LocalizedObjectAnnotation', ) - text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + text_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="EntityAnnotation", + message='EntityAnnotation', ) full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation: "SafeSearchAnnotation" = proto.Field( + safe_search_annotation: 'SafeSearchAnnotation' = proto.Field( proto.MESSAGE, number=6, - message="SafeSearchAnnotation", + message='SafeSearchAnnotation', ) - image_properties_annotation: "ImageProperties" = proto.Field( + image_properties_annotation: 'ImageProperties' = proto.Field( proto.MESSAGE, number=8, - message="ImageProperties", + message='ImageProperties', ) - crop_hints_annotation: "CropHintsAnnotation" = proto.Field( + crop_hints_annotation: 'CropHintsAnnotation' = proto.Field( proto.MESSAGE, number=11, - message="CropHintsAnnotation", + message='CropHintsAnnotation', ) web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, @@ -1175,10 +1170,10 @@ class AnnotateImageResponse(proto.Message): number=9, message=status_pb2.Status, ) - context: "ImageAnnotationContext" = proto.Field( + context: 'ImageAnnotationContext' = proto.Field( proto.MESSAGE, number=21, - message="ImageAnnotationContext", + message='ImageAnnotationContext', ) @@ -1196,15 +1191,15 @@ class AnnotateFileResponse(proto.Message): the file. """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) @@ -1218,10 +1213,10 @@ class BatchAnnotateImagesRequest(proto.Message): batch. """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) @@ -1234,10 +1229,10 @@ class BatchAnnotateImagesResponse(proto.Message): requests within the batch. """ - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) @@ -1257,25 +1252,25 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=4, - message="OutputConfig", + message='OutputConfig', ) @@ -1288,10 +1283,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=1, - message="OutputConfig", + message='OutputConfig', ) @@ -1305,10 +1300,10 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): requests for this batch. """ - requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( + requests: MutableSequence['AsyncAnnotateFileRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileRequest", + message='AsyncAnnotateFileRequest', ) @@ -1322,10 +1317,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( + responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileResponse", + message='AsyncAnnotateFileResponse', ) @@ -1342,10 +1337,10 @@ class InputConfig(proto.Message): supported. Wildcards are not supported. """ - gcs_source: "GcsSource" = proto.Field( + gcs_source: 'GcsSource' = proto.Field( proto.MESSAGE, number=1, - message="GcsSource", + message='GcsSource', ) mime_type: str = proto.Field( proto.STRING, @@ -1374,10 +1369,10 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination: "GcsDestination" = proto.Field( + gcs_destination: 'GcsDestination' = proto.Field( proto.MESSAGE, number=1, - message="GcsDestination", + message='GcsDestination', ) batch_size: int = proto.Field( proto.INT32, @@ -1416,9 +1411,9 @@ class GcsDestination(proto.Message): Examples: - - File: gs://bucket-name/filename.json - - Prefix: gs://bucket-name/prefix/here/ - - File: gs://bucket-name/prefix/here + - File: gs://bucket-name/filename.json + - Prefix: gs://bucket-name/prefix/here/ + - File: gs://bucket-name/prefix/here If multiple outputs, each response is still AnnotateFileResponse, each of which contains some subset of @@ -1445,7 +1440,6 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ - class State(proto.Enum): r"""Batch operation states. diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search.py index 4cd22fcf75e0..0091ec408990 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search.py @@ -17,16 +17,18 @@ from typing import MutableMapping, MutableSequence -from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.vision_v1p3beta1.types import geometry, product_search_service +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.protobuf import timestamp_pb2 # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p3beta1", + package='google.cloud.vision.v1p3beta1', manifest={ - "ProductSearchParams", - "ProductSearchResults", + 'ProductSearchParams', + 'ProductSearchResults', }, ) @@ -194,17 +196,15 @@ class GroupedResult(proto.Message): number=1, message=geometry.BoundingPoly, ) - results: MutableSequence["ProductSearchResults.Result"] = proto.RepeatedField( + results: MutableSequence['ProductSearchResults.Result'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="ProductSearchResults.Result", + message='ProductSearchResults.Result', ) - object_annotations: MutableSequence[ - "ProductSearchResults.ObjectAnnotation" - ] = proto.RepeatedField( + object_annotations: MutableSequence['ProductSearchResults.ObjectAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="ProductSearchResults.ObjectAnnotation", + message='ProductSearchResults.ObjectAnnotation', ) index_time: timestamp_pb2.Timestamp = proto.Field( diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search_service.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search_service.py index b082ad202abf..e09d1ec17218 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search_service.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/product_search_service.py @@ -17,45 +17,46 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1p3beta1.types import geometry from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1p3beta1.types import geometry __protobuf__ = proto.module( - package="google.cloud.vision.v1p3beta1", + package='google.cloud.vision.v1p3beta1', manifest={ - "Product", - "ProductSet", - "ReferenceImage", - "CreateProductRequest", - "ListProductsRequest", - "ListProductsResponse", - "GetProductRequest", - "UpdateProductRequest", - "DeleteProductRequest", - "CreateProductSetRequest", - "ListProductSetsRequest", - "ListProductSetsResponse", - "GetProductSetRequest", - "UpdateProductSetRequest", - "DeleteProductSetRequest", - "CreateReferenceImageRequest", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "GetReferenceImageRequest", - "DeleteReferenceImageRequest", - "AddProductToProductSetRequest", - "RemoveProductFromProductSetRequest", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "BatchOperationMetadata", + 'Product', + 'ProductSet', + 'ReferenceImage', + 'CreateProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'CreateProductSetRequest', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'GetProductSetRequest', + 'UpdateProductSetRequest', + 'DeleteProductSetRequest', + 'CreateReferenceImageRequest', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'GetReferenceImageRequest', + 'DeleteReferenceImageRequest', + 'AddProductToProductSetRequest', + 'RemoveProductFromProductSetRequest', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'BatchOperationMetadata', }, ) @@ -268,10 +269,10 @@ class CreateProductRequest(proto.Message): proto.STRING, number=1, ) - product: "Product" = proto.Field( + product: 'Product' = proto.Field( proto.MESSAGE, number=2, - message="Product", + message='Product', ) product_id: str = proto.Field( proto.STRING, @@ -326,10 +327,10 @@ class ListProductsResponse(proto.Message): def raw_page(self): return self - products: MutableSequence["Product"] = proto.RepeatedField( + products: MutableSequence['Product'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Product", + message='Product', ) next_page_token: str = proto.Field( proto.STRING, @@ -369,10 +370,10 @@ class UpdateProductRequest(proto.Message): ``product_labels``, ``display_name``, and ``description``. """ - product: "Product" = proto.Field( + product: 'Product' = proto.Field( proto.MESSAGE, number=1, - message="Product", + message='Product', ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -421,10 +422,10 @@ class CreateProductSetRequest(proto.Message): proto.STRING, number=1, ) - product_set: "ProductSet" = proto.Field( + product_set: 'ProductSet' = proto.Field( proto.MESSAGE, number=2, - message="ProductSet", + message='ProductSet', ) product_set_id: str = proto.Field( proto.STRING, @@ -479,10 +480,10 @@ class ListProductSetsResponse(proto.Message): def raw_page(self): return self - product_sets: MutableSequence["ProductSet"] = proto.RepeatedField( + product_sets: MutableSequence['ProductSet'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ProductSet", + message='ProductSet', ) next_page_token: str = proto.Field( proto.STRING, @@ -521,10 +522,10 @@ class UpdateProductSetRequest(proto.Message): ``display_name``. """ - product_set: "ProductSet" = proto.Field( + product_set: 'ProductSet' = proto.Field( proto.MESSAGE, number=1, - message="ProductSet", + message='ProductSet', ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -575,10 +576,10 @@ class CreateReferenceImageRequest(proto.Message): proto.STRING, number=1, ) - reference_image: "ReferenceImage" = proto.Field( + reference_image: 'ReferenceImage' = proto.Field( proto.MESSAGE, number=2, - message="ReferenceImage", + message='ReferenceImage', ) reference_image_id: str = proto.Field( proto.STRING, @@ -639,10 +640,10 @@ class ListReferenceImagesResponse(proto.Message): def raw_page(self): return self - reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( + reference_images: MutableSequence['ReferenceImage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ReferenceImage", + message='ReferenceImage', ) page_size: int = proto.Field( proto.INT32, @@ -793,10 +794,10 @@ class ListProductsInProductSetResponse(proto.Message): def raw_page(self): return self - products: MutableSequence["Product"] = proto.RepeatedField( + products: MutableSequence['Product'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Product", + message='Product', ) next_page_token: str = proto.Field( proto.STRING, @@ -892,11 +893,11 @@ class ImportProductSetsInputConfig(proto.Message): This field is a member of `oneof`_ ``source``. """ - gcs_source: "ImportProductSetsGcsSource" = proto.Field( + gcs_source: 'ImportProductSetsGcsSource' = proto.Field( proto.MESSAGE, number=1, - oneof="source", - message="ImportProductSetsGcsSource", + oneof='source', + message='ImportProductSetsGcsSource', ) @@ -918,10 +919,10 @@ class ImportProductSetsRequest(proto.Message): proto.STRING, number=1, ) - input_config: "ImportProductSetsInputConfig" = proto.Field( + input_config: 'ImportProductSetsInputConfig' = proto.Field( proto.MESSAGE, number=2, - message="ImportProductSetsInputConfig", + message='ImportProductSetsInputConfig', ) @@ -947,10 +948,10 @@ class ImportProductSetsResponse(proto.Message): line 0. """ - reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( + reference_images: MutableSequence['ReferenceImage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ReferenceImage", + message='ReferenceImage', ) statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, @@ -977,7 +978,6 @@ class BatchOperationMetadata(proto.Message): [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. """ - class State(proto.Enum): r"""Enumerates the possible states that the batch request can be in. diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/text_annotation.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/text_annotation.py index 660990572b2e..c769050195f3 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/text_annotation.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/text_annotation.py @@ -21,15 +21,16 @@ from google.cloud.vision_v1p3beta1.types import geometry + __protobuf__ = proto.module( - package="google.cloud.vision.v1p3beta1", + package='google.cloud.vision.v1p3beta1', manifest={ - "TextAnnotation", - "Page", - "Block", - "Paragraph", - "Word", - "Symbol", + 'TextAnnotation', + 'Page', + 'Block', + 'Paragraph', + 'Word', + 'Symbol', }, ) @@ -81,7 +82,6 @@ class DetectedBreak(proto.Message): is_prefix (bool): True if break prepends the element. """ - class BreakType(proto.Enum): r"""Enum to denote the type of break found. New line, space etc. @@ -108,10 +108,10 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( + type_: 'TextAnnotation.DetectedBreak.BreakType' = proto.Field( proto.ENUM, number=1, - enum="TextAnnotation.DetectedBreak.BreakType", + enum='TextAnnotation.DetectedBreak.BreakType', ) is_prefix: bool = proto.Field( proto.BOOL, @@ -129,23 +129,21 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence[ - "TextAnnotation.DetectedLanguage" - ] = proto.RepeatedField( + detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="TextAnnotation.DetectedLanguage", + message='TextAnnotation.DetectedLanguage', ) - detected_break: "TextAnnotation.DetectedBreak" = proto.Field( + detected_break: 'TextAnnotation.DetectedBreak' = proto.Field( proto.MESSAGE, number=2, - message="TextAnnotation.DetectedBreak", + message='TextAnnotation.DetectedBreak', ) - pages: MutableSequence["Page"] = proto.RepeatedField( + pages: MutableSequence['Page'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Page", + message='Page', ) text: str = proto.Field( proto.STRING, @@ -172,10 +170,10 @@ class Page(proto.Message): Confidence of the OCR results on the page. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) width: int = proto.Field( proto.INT32, @@ -185,10 +183,10 @@ class Page(proto.Message): proto.INT32, number=3, ) - blocks: MutableSequence["Block"] = proto.RepeatedField( + blocks: MutableSequence['Block'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="Block", + message='Block', ) confidence: float = proto.Field( proto.FLOAT, @@ -210,24 +208,24 @@ class Block(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: + - when the text is horizontal it might look like: - :: + :: - 0----1 - | | - 3----2 + 0----1 + | | + 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: + - when it's rotated 180 degrees around the top-left corner + it becomes: - :: + :: - 2----3 - | | - 1----0 + 2----3 + | | + 1----0 - and the vertice order will still be (0, 1, 2, 3). + and the vertice order will still be (0, 1, 2, 3). paragraphs (MutableSequence[google.cloud.vision_v1p3beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). @@ -237,7 +235,6 @@ class Block(proto.Message): confidence (float): Confidence of the OCR results on the block. Range [0, 1]. """ - class BlockType(proto.Enum): r"""Type of a block (text, image etc) as identified by OCR. @@ -262,20 +259,20 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( + paragraphs: MutableSequence['Paragraph'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Paragraph", + message='Paragraph', ) block_type: BlockType = proto.Field( proto.ENUM, @@ -303,11 +300,11 @@ class Paragraph(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). words (MutableSequence[google.cloud.vision_v1p3beta1.types.Word]): List of words in this paragraph. confidence (float): @@ -315,20 +312,20 @@ class Paragraph(proto.Message): 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words: MutableSequence["Word"] = proto.RepeatedField( + words: MutableSequence['Word'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Word", + message='Word', ) confidence: float = proto.Field( proto.FLOAT, @@ -349,11 +346,11 @@ class Word(proto.Message): represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). symbols (MutableSequence[google.cloud.vision_v1p3beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural @@ -362,20 +359,20 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols: MutableSequence["Symbol"] = proto.RepeatedField( + symbols: MutableSequence['Symbol'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Symbol", + message='Symbol', ) confidence: float = proto.Field( proto.FLOAT, @@ -397,11 +394,11 @@ class Symbol(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertice order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). text (str): The actual UTF-8 representation of the symbol. @@ -409,10 +406,10 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/web_detection.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/web_detection.py index 887e53444d05..3371df697a28 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/web_detection.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/types/web_detection.py @@ -19,10 +19,11 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p3beta1", + package='google.cloud.vision.v1p3beta1', manifest={ - "WebDetection", + 'WebDetection', }, ) @@ -135,19 +136,15 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) - partial_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) class WebLabel(proto.Message): diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/__init__.py index f921e4ab9124..63c67b58d8fb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/__init__.py @@ -13,11 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import sys +from google.cloud.vision_v1p4beta1 import gapic_version as package_version import google.api_core as api_core - -from google.cloud.vision_v1p4beta1 import gapic_version as package_version +import sys __version__ = package_version.__version__ @@ -28,126 +27,127 @@ # this code path once we drop support for Python 3.7 import importlib_metadata as metadata -from google.cloud.vision_helpers import VisionHelpers -from google.cloud.vision_helpers.decorators import add_single_feature_methods +from .services.image_annotator import ImageAnnotatorClient from .services.image_annotator import ImageAnnotatorAsyncClient -from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient -from .services.product_search import ProductSearchAsyncClient, ProductSearchClient -from .types.face import Celebrity, FaceRecognitionParams, FaceRecognitionResult -from .types.geometry import BoundingPoly, NormalizedVertex, Position, Vertex -from .types.image_annotator import ( - AnnotateFileRequest, - AnnotateFileResponse, - AnnotateImageRequest, - AnnotateImageResponse, - AsyncAnnotateFileRequest, - AsyncAnnotateFileResponse, - AsyncBatchAnnotateFilesRequest, - AsyncBatchAnnotateFilesResponse, - AsyncBatchAnnotateImagesRequest, - AsyncBatchAnnotateImagesResponse, - BatchAnnotateFilesRequest, - BatchAnnotateFilesResponse, - BatchAnnotateImagesRequest, - BatchAnnotateImagesResponse, - ColorInfo, - CropHint, - CropHintsAnnotation, - CropHintsParams, - DominantColorsAnnotation, - EntityAnnotation, - FaceAnnotation, - Feature, - GcsDestination, - GcsSource, - Image, - ImageAnnotationContext, - ImageContext, - ImageProperties, - ImageSource, - InputConfig, - LatLongRect, - Likelihood, - LocalizedObjectAnnotation, - LocationInfo, - OperationMetadata, - OutputConfig, - Property, - SafeSearchAnnotation, - TextDetectionParams, - WebDetectionParams, -) -from .types.product_search import ProductSearchParams, ProductSearchResults -from .types.product_search_service import ( - AddProductToProductSetRequest, - BatchOperationMetadata, - CreateProductRequest, - CreateProductSetRequest, - CreateReferenceImageRequest, - DeleteProductRequest, - DeleteProductSetRequest, - DeleteReferenceImageRequest, - GetProductRequest, - GetProductSetRequest, - GetReferenceImageRequest, - ImportProductSetsGcsSource, - ImportProductSetsInputConfig, - ImportProductSetsRequest, - ImportProductSetsResponse, - ListProductSetsRequest, - ListProductSetsResponse, - ListProductsInProductSetRequest, - ListProductsInProductSetResponse, - ListProductsRequest, - ListProductsResponse, - ListReferenceImagesRequest, - ListReferenceImagesResponse, - Product, - ProductSet, - ProductSetPurgeConfig, - PurgeProductsRequest, - ReferenceImage, - RemoveProductFromProductSetRequest, - UpdateProductRequest, - UpdateProductSetRequest, -) -from .types.text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word +from .services.product_search import ProductSearchClient +from .services.product_search import ProductSearchAsyncClient + +from .types.face import Celebrity +from .types.face import FaceRecognitionParams +from .types.face import FaceRecognitionResult +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileRequest +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import AsyncBatchAnnotateImagesRequest +from .types.image_annotator import AsyncBatchAnnotateImagesResponse +from .types.image_annotator import BatchAnnotateFilesRequest +from .types.image_annotator import BatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import LocalizedObjectAnnotation +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import TextDetectionParams +from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood +from .types.product_search import ProductSearchParams +from .types.product_search import ProductSearchResults +from .types.product_search_service import AddProductToProductSetRequest +from .types.product_search_service import BatchOperationMetadata +from .types.product_search_service import CreateProductRequest +from .types.product_search_service import CreateProductSetRequest +from .types.product_search_service import CreateReferenceImageRequest +from .types.product_search_service import DeleteProductRequest +from .types.product_search_service import DeleteProductSetRequest +from .types.product_search_service import DeleteReferenceImageRequest +from .types.product_search_service import GetProductRequest +from .types.product_search_service import GetProductSetRequest +from .types.product_search_service import GetReferenceImageRequest +from .types.product_search_service import ImportProductSetsGcsSource +from .types.product_search_service import ImportProductSetsInputConfig +from .types.product_search_service import ImportProductSetsRequest +from .types.product_search_service import ImportProductSetsResponse +from .types.product_search_service import ListProductSetsRequest +from .types.product_search_service import ListProductSetsResponse +from .types.product_search_service import ListProductsInProductSetRequest +from .types.product_search_service import ListProductsInProductSetResponse +from .types.product_search_service import ListProductsRequest +from .types.product_search_service import ListProductsResponse +from .types.product_search_service import ListReferenceImagesRequest +from .types.product_search_service import ListReferenceImagesResponse +from .types.product_search_service import Product +from .types.product_search_service import ProductSet +from .types.product_search_service import ProductSetPurgeConfig +from .types.product_search_service import PurgeProductsRequest +from .types.product_search_service import ReferenceImage +from .types.product_search_service import RemoveProductFromProductSetRequest +from .types.product_search_service import UpdateProductRequest +from .types.product_search_service import UpdateProductSetRequest +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word from .types.web_detection import WebDetection -if hasattr(api_core, "check_python_version") and hasattr( - api_core, "check_dependency_versions" -): # pragma: NO COVER - api_core.check_python_version("google.cloud.vision_v1p4beta1") # type: ignore - api_core.check_dependency_versions("google.cloud.vision_v1p4beta1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.cloud.vision_v1p4beta1") # type: ignore + api_core.check_dependency_versions("google.cloud.vision_v1p4beta1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: - import sys import warnings + import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.vision_v1p4beta1" if sys.version_info < (3, 9): - warnings.warn( - "You are using a non-supported Python version " - + f"({_py_version_str}). Google will not post any further " - + f"updates to {_package_label} supporting this Python version. " - + "Please upgrade to the latest Python version, or at " - + f"least to Python 3.9, and then update {_package_label}.", - FutureWarning, - ) + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning) if sys.version_info[:2] == (3, 9): - warnings.warn( - f"You are using a Python version ({_py_version_str}) " - + f"which Google will stop supporting in {_package_label} in " - + "January 2026. Please " - + "upgrade to the latest Python version, or at " - + "least to Python 3.10, before then, and " - + f"then update {_package_label}.", - FutureWarning, - ) + warnings.warn(f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -185,127 +185,116 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn( - f"Package {_package_label} depends on " - + f"{_dependency_package}, currently installed at version " - + f"{_version_used_string}. Future updates to " - + f"{_package_label} will require {_dependency_package} at " - + f"version {_next_supported_version} or higher{_recommendation}." - + " Please ensure " - + "that either (a) your Python environment doesn't pin the " - + f"version of {_dependency_package}, so that updates to " - + f"{_package_label} can require the higher version, or " - + "(b) you manually update your Python environment to use at " - + f"least version {_next_supported_version} of " - + f"{_dependency_package}.", - FutureWarning, - ) + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) except Exception: - warnings.warn( - "Could not determine the version of Python " - + "currently being used. To continue receiving " - + "updates for {_package_label}, ensure you are " - + "using a supported version of Python; see " - + "https://devguide.python.org/versions/" - ) - - -@add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): - __doc__ = IacImageAnnotatorClient.__doc__ - Feature = Feature - + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") __all__ = ( - "ImageAnnotatorAsyncClient", - "ProductSearchAsyncClient", - "AddProductToProductSetRequest", - "AnnotateFileRequest", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "BatchOperationMetadata", - "Block", - "BoundingPoly", - "Celebrity", - "ColorInfo", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "FaceRecognitionParams", - "FaceRecognitionResult", - "Feature", - "GcsDestination", - "GcsSource", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "Image", - "ImageAnnotationContext", - "ImageAnnotatorClient", - "ImageContext", - "ImageProperties", - "ImageSource", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "InputConfig", - "LatLongRect", - "Likelihood", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "LocalizedObjectAnnotation", - "LocationInfo", - "NormalizedVertex", - "OperationMetadata", - "OutputConfig", - "Page", - "Paragraph", - "Position", - "Product", - "ProductSearchClient", - "ProductSearchParams", - "ProductSearchResults", - "ProductSet", - "ProductSetPurgeConfig", - "Property", - "PurgeProductsRequest", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "SafeSearchAnnotation", - "Symbol", - "TextAnnotation", - "TextDetectionParams", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Vertex", - "WebDetection", - "WebDetectionParams", - "Word", + 'ImageAnnotatorAsyncClient', + 'ProductSearchAsyncClient', +'AddProductToProductSetRequest', +'AnnotateFileRequest', +'AnnotateFileResponse', +'AnnotateImageRequest', +'AnnotateImageResponse', +'AsyncAnnotateFileRequest', +'AsyncAnnotateFileResponse', +'AsyncBatchAnnotateFilesRequest', +'AsyncBatchAnnotateFilesResponse', +'AsyncBatchAnnotateImagesRequest', +'AsyncBatchAnnotateImagesResponse', +'BatchAnnotateFilesRequest', +'BatchAnnotateFilesResponse', +'BatchAnnotateImagesRequest', +'BatchAnnotateImagesResponse', +'BatchOperationMetadata', +'Block', +'BoundingPoly', +'Celebrity', +'ColorInfo', +'CreateProductRequest', +'CreateProductSetRequest', +'CreateReferenceImageRequest', +'CropHint', +'CropHintsAnnotation', +'CropHintsParams', +'DeleteProductRequest', +'DeleteProductSetRequest', +'DeleteReferenceImageRequest', +'DominantColorsAnnotation', +'EntityAnnotation', +'FaceAnnotation', +'FaceRecognitionParams', +'FaceRecognitionResult', +'Feature', +'GcsDestination', +'GcsSource', +'GetProductRequest', +'GetProductSetRequest', +'GetReferenceImageRequest', +'Image', +'ImageAnnotationContext', +'ImageAnnotatorClient', +'ImageContext', +'ImageProperties', +'ImageSource', +'ImportProductSetsGcsSource', +'ImportProductSetsInputConfig', +'ImportProductSetsRequest', +'ImportProductSetsResponse', +'InputConfig', +'LatLongRect', +'Likelihood', +'ListProductSetsRequest', +'ListProductSetsResponse', +'ListProductsInProductSetRequest', +'ListProductsInProductSetResponse', +'ListProductsRequest', +'ListProductsResponse', +'ListReferenceImagesRequest', +'ListReferenceImagesResponse', +'LocalizedObjectAnnotation', +'LocationInfo', +'NormalizedVertex', +'OperationMetadata', +'OutputConfig', +'Page', +'Paragraph', +'Position', +'Product', +'ProductSearchClient', +'ProductSearchParams', +'ProductSearchResults', +'ProductSet', +'ProductSetPurgeConfig', +'Property', +'PurgeProductsRequest', +'ReferenceImage', +'RemoveProductFromProductSetRequest', +'SafeSearchAnnotation', +'Symbol', +'TextAnnotation', +'TextDetectionParams', +'UpdateProductRequest', +'UpdateProductSetRequest', +'Vertex', +'WebDetection', +'WebDetectionParams', +'Word', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py index c7f40549e472..b1663fdd632d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ImageAnnotatorAsyncClient from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient __all__ = ( - "ImageAnnotatorClient", - "ImageAnnotatorAsyncClient", + 'ImageAnnotatorClient', + 'ImageAnnotatorAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py index 82d9164b0b9a..bc978c86493b 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from google.cloud.vision_v1p4beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p4beta1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -46,23 +36,19 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore - from google.cloud.vision_v1p4beta1.types import image_annotator - -from .client import ImageAnnotatorClient -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ImageAnnotatorAsyncClient: """Service that performs Google Cloud Vision API detection tasks over client images, such as face, landmark, logo, label, and @@ -83,30 +69,16 @@ class ImageAnnotatorAsyncClient: parse_product_path = staticmethod(ImageAnnotatorClient.parse_product_path) product_set_path = staticmethod(ImageAnnotatorClient.product_set_path) parse_product_set_path = staticmethod(ImageAnnotatorClient.parse_product_set_path) - common_billing_account_path = staticmethod( - ImageAnnotatorClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ImageAnnotatorClient.parse_common_billing_account_path - ) + common_billing_account_path = staticmethod(ImageAnnotatorClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageAnnotatorClient.parse_common_billing_account_path) common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) - parse_common_folder_path = staticmethod( - ImageAnnotatorClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ImageAnnotatorClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ImageAnnotatorClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ImageAnnotatorClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageAnnotatorClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageAnnotatorClient.parse_common_organization_path) common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) - parse_common_project_path = staticmethod( - ImageAnnotatorClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ImageAnnotatorClient.parse_common_project_path) common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) - parse_common_location_path = staticmethod( - ImageAnnotatorClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ImageAnnotatorClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -142,9 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -207,16 +177,12 @@ def universe_domain(self) -> str: get_transport_class = ImageAnnotatorClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator async client. Args: @@ -271,43 +237,31 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p4beta1.ImageAnnotatorAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - async def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + async def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -365,14 +319,10 @@ async def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -386,9 +336,7 @@ async def sample_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -404,17 +352,14 @@ async def sample_batch_annotate_images(): # Done; return the response. return response - async def batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateFilesResponse: + async def batch_annotate_files(self, + request: Optional[Union[image_annotator.BatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation for a batch of files. Now only "application/pdf", "image/tiff" and "image/gif" are supported. @@ -479,14 +424,10 @@ async def sample_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -500,9 +441,7 @@ async def sample_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_annotate_files - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_annotate_files] # Validate the universe domain. self._client._validate_universe_domain() @@ -518,20 +457,15 @@ async def sample_batch_annotate_files(): # Done; return the response. return response - async def async_batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - output_config: Optional[image_annotator.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def async_batch_annotate_images(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + output_config: Optional[image_annotator.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of images. @@ -613,14 +547,10 @@ async def sample_async_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests, output_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -636,9 +566,7 @@ async def sample_async_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.async_batch_annotate_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.async_batch_annotate_images] # Validate the universe domain. self._client._validate_universe_domain() @@ -662,19 +590,14 @@ async def sample_async_batch_annotate_images(): # Done; return the response. return response - async def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be @@ -745,14 +668,10 @@ async def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -766,9 +685,7 @@ async def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.async_batch_annotate_files - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.async_batch_annotate_files] # Validate the universe domain. self._client._validate_universe_domain() @@ -798,13 +715,12 @@ async def __aenter__(self) -> "ImageAnnotatorAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorAsyncClient",) +__all__ = ( + "ImageAnnotatorAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/client.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/client.py index bd2be3894228..a2b1c6058f09 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1p4beta1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p4beta1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -63,10 +50,8 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore - from google.cloud.vision_v1p4beta1.types import image_annotator - -from .transports.base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ImageAnnotatorGrpcTransport from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .transports.rest import ImageAnnotatorRestTransport @@ -79,18 +64,14 @@ class ImageAnnotatorClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - - _transport_registry = ( - OrderedDict() - ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] _transport_registry["grpc"] = ImageAnnotatorGrpcTransport _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport _transport_registry["rest"] = ImageAnnotatorRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ImageAnnotatorTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. Args: @@ -166,16 +147,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -214,7 +193,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ImageAnnotatorClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -231,132 +211,84 @@ def transport(self) -> ImageAnnotatorTransport: return self._transport @staticmethod - def product_path( - project: str, - location: str, - product: str, - ) -> str: + def product_path(project: str,location: str,product: str,) -> str: """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + return "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) @staticmethod - def parse_product_path(path: str) -> Dict[str, str]: + def parse_product_path(path: str) -> Dict[str,str]: """Parses a product path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def product_set_path( - project: str, - location: str, - product_set: str, - ) -> str: + def product_set_path(project: str,location: str,product_set: str,) -> str: """Returns a fully-qualified product_set string.""" - return ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + return "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) @staticmethod - def parse_product_set_path(path: str) -> Dict[str, str]: + def parse_product_set_path(path: str) -> Dict[str,str]: """Parses a product_set path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -388,18 +320,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ImageAnnotatorClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -412,9 +340,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -439,9 +365,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -464,9 +388,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -482,25 +404,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -536,18 +450,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -580,16 +491,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageAnnotatorTransport, Callable[..., ImageAnnotatorTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the image annotator client. Args: @@ -644,24 +551,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ImageAnnotatorClient._read_environment_variables() - self._client_cert_source = ImageAnnotatorClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ImageAnnotatorClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageAnnotatorClient._read_environment_variables() + self._client_cert_source = ImageAnnotatorClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageAnnotatorClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -672,9 +569,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -683,10 +578,8 @@ def __init__( if transport_provided: # transport is a ImageAnnotatorTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -695,29 +588,20 @@ def __init__( self._transport = cast(ImageAnnotatorTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ImageAnnotatorClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ImageAnnotatorClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport] - ] = ( + transport_init: Union[Type[ImageAnnotatorTransport], Callable[..., ImageAnnotatorTransport]] = ( ImageAnnotatorClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ImageAnnotatorTransport], transport) @@ -736,41 +620,28 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p4beta1.ImageAnnotatorClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "credentialsType": None, - }, + } ) - def batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def batch_annotate_images(self, + request: Optional[Union[image_annotator.BatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of images. @@ -828,14 +699,10 @@ def sample_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -864,17 +731,14 @@ def sample_batch_annotate_images(): # Done; return the response. return response - def batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.BatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateFilesResponse: + def batch_annotate_files(self, + request: Optional[Union[image_annotator.BatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation for a batch of files. Now only "application/pdf", "image/tiff" and "image/gif" are supported. @@ -939,14 +803,10 @@ def sample_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -975,20 +835,15 @@ def sample_batch_annotate_files(): # Done; return the response. return response - def async_batch_annotate_images( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AnnotateImageRequest] - ] = None, - output_config: Optional[image_annotator.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def async_batch_annotate_images(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AnnotateImageRequest]] = None, + output_config: Optional[image_annotator.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of images. @@ -1070,14 +925,10 @@ def sample_async_batch_annotate_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests, output_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1092,9 +943,7 @@ def sample_async_batch_annotate_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.async_batch_annotate_images - ] + rpc = self._transport._wrapped_methods[self._transport.async_batch_annotate_images] # Validate the universe domain. self._validate_universe_domain() @@ -1118,19 +967,14 @@ def sample_async_batch_annotate_images(): # Done; return the response. return response - def async_batch_annotate_files( - self, - request: Optional[ - Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] - ] = None, - *, - requests: Optional[ - MutableSequence[image_annotator.AsyncAnnotateFileRequest] - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def async_batch_annotate_files(self, + request: Optional[Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict]] = None, + *, + requests: Optional[MutableSequence[image_annotator.AsyncAnnotateFileRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be @@ -1201,14 +1045,10 @@ def sample_async_batch_annotate_files(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [requests] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1221,9 +1061,7 @@ def sample_async_batch_annotate_files(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.async_batch_annotate_files - ] + rpc = self._transport._wrapped_methods[self._transport.async_batch_annotate_files] # Validate the universe domain. self._validate_universe_domain() @@ -1261,11 +1099,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ImageAnnotatorClient",) +__all__ = ( + "ImageAnnotatorClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py index 1de28b3fb87a..d3a583db5759 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ImageAnnotatorTransport from .grpc import ImageAnnotatorGrpcTransport from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport -from .rest import ImageAnnotatorRestInterceptor, ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestTransport +from .rest import ImageAnnotatorRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] -_transport_registry["grpc"] = ImageAnnotatorGrpcTransport -_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport -_transport_registry["rest"] = ImageAnnotatorRestTransport +_transport_registry['grpc'] = ImageAnnotatorGrpcTransport +_transport_registry['grpc_asyncio'] = ImageAnnotatorGrpcAsyncIOTransport +_transport_registry['rest'] = ImageAnnotatorRestTransport __all__ = ( - "ImageAnnotatorTransport", - "ImageAnnotatorGrpcTransport", - "ImageAnnotatorGrpcAsyncIOTransport", - "ImageAnnotatorRestTransport", - "ImageAnnotatorRestInterceptor", + 'ImageAnnotatorTransport', + 'ImageAnnotatorGrpcTransport', + 'ImageAnnotatorGrpcAsyncIOTransport', + 'ImageAnnotatorRestTransport', + 'ImageAnnotatorRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py index 3534da170b88..f4b7b5f8fb89 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py @@ -16,22 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1p4beta1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.cloud.vision_v1p4beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,25 +41,24 @@ class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -86,8 +85,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -96,38 +93,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -143,7 +133,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -155,7 +146,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -167,7 +159,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -179,20 +172,21 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -202,45 +196,39 @@ def operations_client(self): raise NotImplementedError() @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Union[ - image_annotator.BatchAnnotateImagesResponse, - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Union[ + image_annotator.BatchAnnotateImagesResponse, + Awaitable[image_annotator.BatchAnnotateImagesResponse] + ]]: raise NotImplementedError() @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - Union[ - image_annotator.BatchAnnotateFilesResponse, - Awaitable[image_annotator.BatchAnnotateFilesResponse], - ], - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + Union[ + image_annotator.BatchAnnotateFilesResponse, + Awaitable[image_annotator.BatchAnnotateFilesResponse] + ]]: raise NotImplementedError() @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -248,4 +236,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ImageAnnotatorTransport",) +__all__ = ( + 'ImageAnnotatorTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py index 3a4e2ca1115e..1ead921c247c 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py @@ -16,26 +16,27 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -45,9 +46,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -68,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -79,11 +78,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -98,7 +93,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": client_call_details.method, "response": grpc_response, @@ -123,26 +118,23 @@ class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -266,23 +258,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -318,12 +306,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -343,12 +332,9 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -364,21 +350,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - image_annotator.BatchAnnotateFilesResponse, - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + image_annotator.BatchAnnotateFilesResponse]: r"""Return a callable for the batch annotate files method over gRPC. Service that performs image detection and annotation @@ -401,20 +384,18 @@ def batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_files" not in self._stubs: - self._stubs["batch_annotate_files"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles", + if 'batch_annotate_files' not in self._stubs: + self._stubs['batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles', request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, ) - return self._stubs["batch_annotate_files"] + return self._stubs['batch_annotate_files'] @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + operations_pb2.Operation]: r"""Return a callable for the async batch annotate images method over gRPC. Run asynchronous image detection and annotation for a list of @@ -440,22 +421,18 @@ def async_batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_images" not in self._stubs: - self._stubs[ - "async_batch_annotate_images" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages", + if 'async_batch_annotate_images' not in self._stubs: + self._stubs['async_batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages', request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_images"] + return self._stubs['async_batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + operations_pb2.Operation]: r"""Return a callable for the async batch annotate files method over gRPC. Run asynchronous image detection and annotation for a list of @@ -476,15 +453,13 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def close(self): self._logged_channel.close() @@ -494,4 +469,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ImageAnnotatorGrpcTransport",) +__all__ = ( + 'ImageAnnotatorGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py index f78715e6006e..1ead8feda588 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py @@ -15,31 +15,32 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -47,13 +48,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -74,7 +71,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -85,11 +82,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -104,7 +97,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -134,15 +127,13 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -173,26 +164,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -318,9 +307,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -351,12 +338,9 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - Awaitable[image_annotator.BatchAnnotateImagesResponse], - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse]]: r"""Return a callable for the batch annotate images method over gRPC. Run image detection and annotation for a batch of @@ -372,21 +356,18 @@ def batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_images" not in self._stubs: - self._stubs["batch_annotate_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages", + if 'batch_annotate_images' not in self._stubs: + self._stubs['batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages', request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, ) - return self._stubs["batch_annotate_images"] + return self._stubs['batch_annotate_images'] @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - Awaitable[image_annotator.BatchAnnotateFilesResponse], - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + Awaitable[image_annotator.BatchAnnotateFilesResponse]]: r"""Return a callable for the batch annotate files method over gRPC. Service that performs image detection and annotation @@ -409,21 +390,18 @@ def batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "batch_annotate_files" not in self._stubs: - self._stubs["batch_annotate_files"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles", + if 'batch_annotate_files' not in self._stubs: + self._stubs['batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles', request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, ) - return self._stubs["batch_annotate_files"] + return self._stubs['batch_annotate_files'] @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], - Awaitable[operations_pb2.Operation], - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the async batch annotate images method over gRPC. Run asynchronous image detection and annotation for a list of @@ -449,23 +427,18 @@ def async_batch_annotate_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_images" not in self._stubs: - self._stubs[ - "async_batch_annotate_images" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages", + if 'async_batch_annotate_images' not in self._stubs: + self._stubs['async_batch_annotate_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages', request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_images"] + return self._stubs['async_batch_annotate_images'] @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations_pb2.Operation], - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the async batch annotate files method over gRPC. Run asynchronous image detection and annotation for a list of @@ -486,18 +459,16 @@ def async_batch_annotate_files( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "async_batch_annotate_files" not in self._stubs: - self._stubs[ - "async_batch_annotate_files" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + if 'async_batch_annotate_files' not in self._stubs: + self._stubs['async_batch_annotate_files'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles', request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["async_batch_annotate_files"] + return self._stubs['async_batch_annotate_files'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.batch_annotate_images: self._wrap_method( self.batch_annotate_images, @@ -505,7 +476,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -517,7 +489,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -529,7 +502,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -541,7 +515,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -562,4 +537,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) +__all__ = ( + 'ImageAnnotatorGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest.py index 7bf18d1c4973..8836d99cf1cd 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest.py @@ -13,26 +13,33 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1p4beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseImageAnnotatorRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -41,7 +48,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -110,15 +116,7 @@ def post_batch_annotate_images(self, response): """ - - def pre_async_batch_annotate_files( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.AsyncBatchAnnotateFilesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_async_batch_annotate_files(self, request: image_annotator.AsyncBatchAnnotateFilesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.AsyncBatchAnnotateFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for async_batch_annotate_files Override in a subclass to manipulate the request or metadata @@ -126,9 +124,7 @@ def pre_async_batch_annotate_files( """ return request, metadata - def post_async_batch_annotate_files( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_async_batch_annotate_files(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for async_batch_annotate_files DEPRECATED. Please use the `post_async_batch_annotate_files_with_metadata` @@ -141,11 +137,7 @@ def post_async_batch_annotate_files( """ return response - def post_async_batch_annotate_files_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_async_batch_annotate_files_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for async_batch_annotate_files Override in a subclass to read or manipulate the response or metadata after it @@ -160,14 +152,7 @@ def post_async_batch_annotate_files_with_metadata( """ return response, metadata - def pre_async_batch_annotate_images( - self, - request: image_annotator.AsyncBatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.AsyncBatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_async_batch_annotate_images(self, request: image_annotator.AsyncBatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.AsyncBatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for async_batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -175,9 +160,7 @@ def pre_async_batch_annotate_images( """ return request, metadata - def post_async_batch_annotate_images( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_async_batch_annotate_images(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for async_batch_annotate_images DEPRECATED. Please use the `post_async_batch_annotate_images_with_metadata` @@ -190,11 +173,7 @@ def post_async_batch_annotate_images( """ return response - def post_async_batch_annotate_images_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_async_batch_annotate_images_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for async_batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -209,14 +188,7 @@ def post_async_batch_annotate_images_with_metadata( """ return response, metadata - def pre_batch_annotate_files( - self, - request: image_annotator.BatchAnnotateFilesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateFilesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_files(self, request: image_annotator.BatchAnnotateFilesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_files Override in a subclass to manipulate the request or metadata @@ -224,9 +196,7 @@ def pre_batch_annotate_files( """ return request, metadata - def post_batch_annotate_files( - self, response: image_annotator.BatchAnnotateFilesResponse - ) -> image_annotator.BatchAnnotateFilesResponse: + def post_batch_annotate_files(self, response: image_annotator.BatchAnnotateFilesResponse) -> image_annotator.BatchAnnotateFilesResponse: """Post-rpc interceptor for batch_annotate_files DEPRECATED. Please use the `post_batch_annotate_files_with_metadata` @@ -239,14 +209,7 @@ def post_batch_annotate_files( """ return response - def post_batch_annotate_files_with_metadata( - self, - response: image_annotator.BatchAnnotateFilesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateFilesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_files_with_metadata(self, response: image_annotator.BatchAnnotateFilesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateFilesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_files Override in a subclass to read or manipulate the response or metadata after it @@ -261,14 +224,7 @@ def post_batch_annotate_files_with_metadata( """ return response, metadata - def pre_batch_annotate_images( - self, - request: image_annotator.BatchAnnotateImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_batch_annotate_images(self, request: image_annotator.BatchAnnotateImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for batch_annotate_images Override in a subclass to manipulate the request or metadata @@ -276,9 +232,7 @@ def pre_batch_annotate_images( """ return request, metadata - def post_batch_annotate_images( - self, response: image_annotator.BatchAnnotateImagesResponse - ) -> image_annotator.BatchAnnotateImagesResponse: + def post_batch_annotate_images(self, response: image_annotator.BatchAnnotateImagesResponse) -> image_annotator.BatchAnnotateImagesResponse: """Post-rpc interceptor for batch_annotate_images DEPRECATED. Please use the `post_batch_annotate_images_with_metadata` @@ -291,14 +245,7 @@ def post_batch_annotate_images( """ return response - def post_batch_annotate_images_with_metadata( - self, - response: image_annotator.BatchAnnotateImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - image_annotator.BatchAnnotateImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_batch_annotate_images_with_metadata(self, response: image_annotator.BatchAnnotateImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_annotator.BatchAnnotateImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for batch_annotate_images Override in a subclass to read or manipulate the response or metadata after it @@ -336,21 +283,20 @@ class ImageAnnotatorRestTransport(_BaseImageAnnotatorRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ImageAnnotatorRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ImageAnnotatorRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -394,11 +340,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -414,28 +359,23 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: """ # 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]]] = {} + http_options: Dict[str, List[Dict[str, str]]] = { + } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1p4beta1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p4beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AsyncBatchAnnotateFiles( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, - ImageAnnotatorRestStub, - ): + class _AsyncBatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateFiles") @@ -447,93 +387,77 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.AsyncBatchAnnotateFilesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: image_annotator.AsyncBatchAnnotateFilesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the async batch annotate - files method over HTTP. - - Args: - request (~.image_annotator.AsyncBatchAnnotateFilesRequest): - The request object. Multiple async file annotation - requests are batched into a single - service call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + files method over HTTP. + + Args: + request (~.image_annotator.AsyncBatchAnnotateFilesRequest): + The request object. Multiple async file annotation + requests are batched into a single + service call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_http_options() - request, metadata = self._interceptor.pre_async_batch_annotate_files( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_async_batch_annotate_files(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.AsyncBatchAnnotateFiles", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "httpRequest": http_request, @@ -542,17 +466,7 @@ def __call__( ) # Send the request - response = ( - ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ImageAnnotatorRestTransport._AsyncBatchAnnotateFiles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -565,24 +479,20 @@ def __call__( resp = self._interceptor.post_async_batch_annotate_files(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_async_batch_annotate_files_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.async_batch_annotate_files", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateFiles", "metadata": http_response["headers"], @@ -591,10 +501,7 @@ def __call__( ) return resp - class _AsyncBatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _AsyncBatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.AsyncBatchAnnotateImages") @@ -606,92 +513,76 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.AsyncBatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: image_annotator.AsyncBatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the async batch annotate - images method over HTTP. - - Args: - request (~.image_annotator.AsyncBatchAnnotateImagesRequest): - The request object. Request for async image annotation - for a list of images. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + images method over HTTP. + + Args: + request (~.image_annotator.AsyncBatchAnnotateImagesRequest): + The request object. Request for async image annotation + for a list of images. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_async_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_async_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.AsyncBatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateImages", "httpRequest": http_request, @@ -700,17 +591,7 @@ def __call__( ) # Send the request - response = ( - ImageAnnotatorRestTransport._AsyncBatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ImageAnnotatorRestTransport._AsyncBatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -723,24 +604,20 @@ def __call__( resp = self._interceptor.post_async_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_async_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_async_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.async_batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "AsyncBatchAnnotateImages", "metadata": http_response["headers"], @@ -749,9 +626,7 @@ def __call__( ) return resp - class _BatchAnnotateFiles( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub - ): + class _BatchAnnotateFiles(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateFiles") @@ -763,29 +638,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateFilesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateFilesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateFilesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateFilesResponse: r"""Call the batch annotate files method over HTTP. Args: @@ -805,46 +678,32 @@ def __call__( A list of file annotation responses. """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_files( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_files(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.BatchAnnotateFiles", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "BatchAnnotateFiles", "httpRequest": http_request, @@ -853,15 +712,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateFiles._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateFiles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -876,26 +727,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_files(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_files_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_files_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateFilesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateFilesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.batch_annotate_files", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "BatchAnnotateFiles", "metadata": http_response["headers"], @@ -904,10 +749,7 @@ def __call__( ) return resp - class _BatchAnnotateImages( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, - ImageAnnotatorRestStub, - ): + class _BatchAnnotateImages(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages, ImageAnnotatorRestStub): def __hash__(self): return hash("ImageAnnotatorRestTransport.BatchAnnotateImages") @@ -919,29 +761,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: image_annotator.BatchAnnotateImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> image_annotator.BatchAnnotateImagesResponse: + def __call__(self, + request: image_annotator.BatchAnnotateImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_annotator.BatchAnnotateImagesResponse: r"""Call the batch annotate images method over HTTP. Args: @@ -963,46 +803,32 @@ def __call__( """ - http_options = ( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - ) + http_options = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_http_options() - request, metadata = self._interceptor.pre_batch_annotate_images( - request, metadata - ) - transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_batch_annotate_images(request, metadata) + transcoded_request = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_transcoded_request(http_options, request) - body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json( - transcoded_request - ) + body = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.BatchAnnotateImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "httpRequest": http_request, @@ -1011,15 +837,7 @@ def __call__( ) # Send the request - response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ImageAnnotatorRestTransport._BatchAnnotateImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1034,26 +852,20 @@ def __call__( resp = self._interceptor.post_batch_annotate_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_annotate_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_annotate_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - image_annotator.BatchAnnotateImagesResponse.to_json(response) - ) + response_payload = image_annotator.BatchAnnotateImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ImageAnnotatorClient.batch_annotate_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ImageAnnotator", "rpcName": "BatchAnnotateImages", "metadata": http_response["headers"], @@ -1063,46 +875,36 @@ def __call__( return resp @property - def async_batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_files(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + 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._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore + return self._AsyncBatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore @property - def async_batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], operations_pb2.Operation - ]: + def async_batch_annotate_images(self) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + 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._AsyncBatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._AsyncBatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property - def batch_annotate_files( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateFilesRequest], - image_annotator.BatchAnnotateFilesResponse, - ]: + def batch_annotate_files(self) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + image_annotator.BatchAnnotateFilesResponse]: # 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._BatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateFiles(self._session, self._host, self._interceptor) # type: ignore @property - def batch_annotate_images( - self, - ) -> Callable[ - [image_annotator.BatchAnnotateImagesRequest], - image_annotator.BatchAnnotateImagesResponse, - ]: + def batch_annotate_images(self) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse]: # 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._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore + return self._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -1112,4 +914,6 @@ def close(self): self._session.close() -__all__ = ("ImageAnnotatorRestTransport",) +__all__=( + 'ImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest_base.py index 804a391713b9..60e8ac98bc3c 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/image_annotator/transports/rest_base.py @@ -14,16 +14,18 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1p4beta1.types import image_annotator - -from .base import DEFAULT_CLIENT_INFO, ImageAnnotatorTransport +from google.longrunning import operations_pb2 # type: ignore class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): @@ -39,16 +41,14 @@ class _BaseImageAnnotatorRestTransport(ImageAnnotatorTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -72,9 +72,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -85,31 +83,27 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAsyncBatchAnnotateFiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/files:asyncBatchAnnotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/files:asyncBatchAnnotate', + 'body': '*', + }, ] return http_options @@ -124,23 +118,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateFiles._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -149,24 +137,20 @@ class _BaseAsyncBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/images:asyncBatchAnnotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/images:asyncBatchAnnotate', + 'body': '*', + }, ] return http_options @@ -181,23 +165,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseAsyncBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -206,24 +184,20 @@ class _BaseBatchAnnotateFiles: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/files:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/files:annotate', + 'body': '*', + }, ] return http_options @@ -238,23 +212,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateFiles._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -263,24 +231,20 @@ class _BaseBatchAnnotateImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/images:annotate", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/images:annotate', + 'body': '*', + }, ] return http_options @@ -295,26 +259,22 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseImageAnnotatorRestTransport._BaseBatchAnnotateImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__ = ("_BaseImageAnnotatorRestTransport",) +__all__=( + '_BaseImageAnnotatorRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/__init__.py index f2e4fe58e8df..ff3cc167408d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import ProductSearchAsyncClient from .client import ProductSearchClient +from .async_client import ProductSearchAsyncClient __all__ = ( - "ProductSearchClient", - "ProductSearchAsyncClient", + 'ProductSearchClient', + 'ProductSearchAsyncClient', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/async_client.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/async_client.py index 25cfb5dfc83e..2155ab42d303 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/async_client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/async_client.py @@ -13,31 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict import logging as std_logging +from collections import OrderedDict import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p4beta1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -46,48 +36,46 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p4beta1.services.product_search import pagers +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore - -from google.cloud.vision_v1p4beta1.services.product_search import pagers -from google.cloud.vision_v1p4beta1.types import geometry, product_search_service - -from .client import ProductSearchClient -from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport +from .client import ProductSearchClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class ProductSearchAsyncClient: """Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` """ _client: ProductSearchClient @@ -104,33 +92,17 @@ class ProductSearchAsyncClient: product_set_path = staticmethod(ProductSearchClient.product_set_path) parse_product_set_path = staticmethod(ProductSearchClient.parse_product_set_path) reference_image_path = staticmethod(ProductSearchClient.reference_image_path) - parse_reference_image_path = staticmethod( - ProductSearchClient.parse_reference_image_path - ) - common_billing_account_path = staticmethod( - ProductSearchClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - ProductSearchClient.parse_common_billing_account_path - ) + parse_reference_image_path = staticmethod(ProductSearchClient.parse_reference_image_path) + common_billing_account_path = staticmethod(ProductSearchClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProductSearchClient.parse_common_billing_account_path) common_folder_path = staticmethod(ProductSearchClient.common_folder_path) - parse_common_folder_path = staticmethod( - ProductSearchClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - ProductSearchClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - ProductSearchClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(ProductSearchClient.parse_common_folder_path) + common_organization_path = staticmethod(ProductSearchClient.common_organization_path) + parse_common_organization_path = staticmethod(ProductSearchClient.parse_common_organization_path) common_project_path = staticmethod(ProductSearchClient.common_project_path) - parse_common_project_path = staticmethod( - ProductSearchClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(ProductSearchClient.parse_common_project_path) common_location_path = staticmethod(ProductSearchClient.common_location_path) - parse_common_location_path = staticmethod( - ProductSearchClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(ProductSearchClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -166,9 +138,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -231,16 +201,12 @@ def universe_domain(self) -> str: get_transport_class = ProductSearchClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the product search async client. Args: @@ -295,49 +261,39 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p4beta1.ProductSearchAsyncClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "credentialsType": None, - }, + } ) - async def create_product_set( - self, - request: Optional[ - Union[product_search_service.CreateProductSetRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product_set: Optional[product_search_service.ProductSet] = None, - product_set_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def create_product_set(self, + request: Optional[Union[product_search_service.CreateProductSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. .. code-block:: python @@ -413,14 +369,10 @@ async def sample_create_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product_set, product_set_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -438,14 +390,14 @@ async def sample_create_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -462,23 +414,20 @@ async def sample_create_product_set(): # Done; return the response. return response - async def list_product_sets( - self, - request: Optional[ - Union[product_search_service.ListProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductSetsAsyncPager: + async def list_product_sets(self, + request: Optional[Union[product_search_service.ListProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductSetsAsyncPager: r"""Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. .. code-block:: python @@ -539,14 +488,10 @@ async def sample_list_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -560,14 +505,14 @@ async def sample_list_product_sets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_product_sets - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_product_sets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -595,22 +540,19 @@ async def sample_list_product_sets(): # Done; return the response. return response - async def get_product_set( - self, - request: Optional[ - Union[product_search_service.GetProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def get_product_set(self, + request: Optional[Union[product_search_service.GetProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -671,14 +613,10 @@ async def sample_get_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -692,14 +630,14 @@ async def sample_get_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -716,27 +654,24 @@ async def sample_get_product_set(): # Done; return the response. return response - async def update_product_set( - self, - request: Optional[ - Union[product_search_service.UpdateProductSetRequest, dict] - ] = None, - *, - product_set: Optional[product_search_service.ProductSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + async def update_product_set(self, + request: Optional[Union[product_search_service.UpdateProductSetRequest, dict]] = None, + *, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. .. code-block:: python @@ -803,14 +738,10 @@ async def sample_update_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product_set, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -826,16 +757,14 @@ async def sample_update_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.update_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product_set.name", request.product_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product_set.name", request.product_set.name), + )), ) # Validate the universe domain. @@ -852,17 +781,14 @@ async def sample_update_product_set(): # Done; return the response. return response - async def delete_product_set( - self, - request: Optional[ - Union[product_search_service.DeleteProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_product_set(self, + request: Optional[Union[product_search_service.DeleteProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a ProductSet. Products and ReferenceImages in the ProductSet are not deleted. @@ -916,14 +842,10 @@ async def sample_delete_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -937,14 +859,14 @@ async def sample_delete_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -958,29 +880,26 @@ async def sample_delete_product_set(): metadata=metadata, ) - async def create_product( - self, - request: Optional[ - Union[product_search_service.CreateProductRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product: Optional[product_search_service.Product] = None, - product_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def create_product(self, + request: Optional[Union[product_search_service.CreateProductRequest, dict]] = None, + *, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. .. code-block:: python @@ -1051,14 +970,10 @@ async def sample_create_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product, product_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1076,14 +991,14 @@ async def sample_create_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1100,23 +1015,20 @@ async def sample_create_product(): # Done; return the response. return response - async def list_products( - self, - request: Optional[ - Union[product_search_service.ListProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsAsyncPager: + async def list_products(self, + request: Optional[Union[product_search_service.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsAsyncPager: r"""Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -1177,14 +1089,10 @@ async def sample_list_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1198,14 +1106,14 @@ async def sample_list_products(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_products - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_products] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1233,20 +1141,19 @@ async def sample_list_products(): # Done; return the response. return response - async def get_product( - self, - request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def get_product(self, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. .. code-block:: python @@ -1302,14 +1209,10 @@ async def sample_get_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1323,14 +1226,14 @@ async def sample_get_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1347,18 +1250,15 @@ async def sample_get_product(): # Done; return the response. return response - async def update_product( - self, - request: Optional[ - Union[product_search_service.UpdateProductRequest, dict] - ] = None, - *, - product: Optional[product_search_service.Product] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + async def update_product(self, + request: Optional[Union[product_search_service.UpdateProductRequest, dict]] = None, + *, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. @@ -1367,14 +1267,14 @@ async def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. .. code-block:: python @@ -1438,14 +1338,10 @@ async def sample_update_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1461,16 +1357,14 @@ async def sample_update_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.update_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product.name", request.product.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), ) # Validate the universe domain. @@ -1487,17 +1381,14 @@ async def sample_update_product(): # Done; return the response. return response - async def delete_product( - self, - request: Optional[ - Union[product_search_service.DeleteProductRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_product(self, + request: Optional[Union[product_search_service.DeleteProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a product and its reference images. Metadata of the product and all its images will be @@ -1552,14 +1443,10 @@ async def sample_delete_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1573,14 +1460,14 @@ async def sample_delete_product(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_product - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_product] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1594,19 +1481,16 @@ async def sample_delete_product(): metadata=metadata, ) - async def create_reference_image( - self, - request: Optional[ - Union[product_search_service.CreateReferenceImageRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - reference_image: Optional[product_search_service.ReferenceImage] = None, - reference_image_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + async def create_reference_image(self, + request: Optional[Union[product_search_service.CreateReferenceImageRequest, dict]] = None, + *, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is @@ -1621,14 +1505,14 @@ async def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. .. code-block:: python @@ -1709,14 +1593,10 @@ async def sample_create_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, reference_image, reference_image_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1734,14 +1614,14 @@ async def sample_create_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.create_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1758,17 +1638,14 @@ async def sample_create_reference_image(): # Done; return the response. return response - async def delete_reference_image( - self, - request: Optional[ - Union[product_search_service.DeleteReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_reference_image(self, + request: Optional[Union[product_search_service.DeleteReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a reference image. The image metadata will be deleted right away, but @@ -1827,14 +1704,10 @@ async def sample_delete_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1848,14 +1721,14 @@ async def sample_delete_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1869,24 +1742,21 @@ async def sample_delete_reference_image(): metadata=metadata, ) - async def list_reference_images( - self, - request: Optional[ - Union[product_search_service.ListReferenceImagesRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListReferenceImagesAsyncPager: + async def list_reference_images(self, + request: Optional[Union[product_search_service.ListReferenceImagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListReferenceImagesAsyncPager: r"""Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. .. code-block:: python @@ -1948,14 +1818,10 @@ async def sample_list_reference_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1969,14 +1835,14 @@ async def sample_list_reference_images(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_reference_images - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_reference_images] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2004,22 +1870,19 @@ async def sample_list_reference_images(): # Done; return the response. return response - async def get_reference_image( - self, - request: Optional[ - Union[product_search_service.GetReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + async def get_reference_image(self, + request: Optional[Union[product_search_service.GetReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. .. code-block:: python @@ -2079,14 +1942,10 @@ async def sample_get_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2100,14 +1959,14 @@ async def sample_get_reference_image(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_reference_image - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.get_reference_image] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2124,18 +1983,15 @@ async def sample_get_reference_image(): # Done; return the response. return response - async def add_product_to_product_set( - self, - request: Optional[ - Union[product_search_service.AddProductToProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def add_product_to_product_set(self, + request: Optional[Union[product_search_service.AddProductToProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is already present, no change is made. @@ -2143,8 +1999,8 @@ async def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. .. code-block:: python @@ -2206,20 +2062,14 @@ async def sample_add_product_to_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.AddProductToProductSetRequest - ): + if not isinstance(request, product_search_service.AddProductToProductSetRequest): request = product_search_service.AddProductToProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2231,14 +2081,14 @@ async def sample_add_product_to_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.add_product_to_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.add_product_to_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2252,18 +2102,15 @@ async def sample_add_product_to_product_set(): metadata=metadata, ) - async def remove_product_from_product_set( - self, - request: Optional[ - Union[product_search_service.RemoveProductFromProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def remove_product_from_product_set(self, + request: Optional[Union[product_search_service.RemoveProductFromProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Removes a Product from the specified ProductSet. .. code-block:: python @@ -2326,20 +2173,14 @@ async def sample_remove_product_from_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.RemoveProductFromProductSetRequest - ): + if not isinstance(request, product_search_service.RemoveProductFromProductSetRequest): request = product_search_service.RemoveProductFromProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2351,14 +2192,14 @@ async def sample_remove_product_from_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.remove_product_from_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_product_from_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2372,25 +2213,22 @@ async def sample_remove_product_from_product_set(): metadata=metadata, ) - async def list_products_in_product_set( - self, - request: Optional[ - Union[product_search_service.ListProductsInProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsInProductSetAsyncPager: + async def list_products_in_product_set(self, + request: Optional[Union[product_search_service.ListProductsInProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsInProductSetAsyncPager: r"""Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -2454,20 +2292,14 @@ async def sample_list_products_in_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.ListProductsInProductSetRequest - ): + if not isinstance(request, product_search_service.ListProductsInProductSetRequest): request = product_search_service.ListProductsInProductSetRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2477,14 +2309,14 @@ async def sample_list_products_in_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_products_in_product_set - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.list_products_in_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2512,20 +2344,15 @@ async def sample_list_products_in_product_set(): # Done; return the response. return response - async def import_product_sets( - self, - request: Optional[ - Union[product_search_service.ImportProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - input_config: Optional[ - product_search_service.ImportProductSetsInputConfig - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def import_product_sets(self, + request: Optional[Union[product_search_service.ImportProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + input_config: Optional[product_search_service.ImportProductSetsInputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. @@ -2615,14 +2442,10 @@ async def sample_import_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2638,14 +2461,14 @@ async def sample_import_product_sets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.import_product_sets - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.import_product_sets] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2670,17 +2493,14 @@ async def sample_import_product_sets(): # Done; return the response. return response - async def purge_products( - self, - request: Optional[ - Union[product_search_service.PurgeProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def purge_products(self, + request: Optional[Union[product_search_service.PurgeProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronous API to delete all Products in a ProductSet or all Products that are in no ProductSet. @@ -2779,14 +2599,10 @@ async def sample_purge_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2800,14 +2616,14 @@ async def sample_purge_products(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.purge_products - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.purge_products] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2838,13 +2654,12 @@ async def __aenter__(self) -> "ProductSearchAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ProductSearchAsyncClient",) +__all__ = ( + "ProductSearchAsyncClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/client.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/client.py index c34d87387b68..805bddb387c5 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/client.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/client.py @@ -19,34 +19,22 @@ import logging as std_logging import os import re -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from google.cloud.vision_v1p4beta1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.vision_v1p4beta1 import gapic_version as package_version - try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -54,7 +42,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -63,15 +50,14 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p4beta1.services.product_search import pagers +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore - -from google.cloud.vision_v1p4beta1.services.product_search import pagers -from google.cloud.vision_v1p4beta1.types import geometry, product_search_service - -from .transports.base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .transports.rest import ProductSearchRestTransport @@ -84,16 +70,14 @@ class ProductSearchClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] _transport_registry["grpc"] = ProductSearchGrpcTransport _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport _transport_registry["rest"] = ProductSearchRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[ProductSearchTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProductSearchTransport]: """Returns an appropriate transport class. Args: @@ -116,22 +100,23 @@ class ProductSearchClient(metaclass=ProductSearchClientMeta): """Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` """ @staticmethod @@ -184,16 +169,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -232,7 +215,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProductSearchClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -249,156 +233,95 @@ def transport(self) -> ProductSearchTransport: return self._transport @staticmethod - def product_path( - project: str, - location: str, - product: str, - ) -> str: + def product_path(project: str,location: str,product: str,) -> str: """Returns a fully-qualified product string.""" - return "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + return "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) @staticmethod - def parse_product_path(path: str) -> Dict[str, str]: + def parse_product_path(path: str) -> Dict[str,str]: """Parses a product path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def product_set_path( - project: str, - location: str, - product_set: str, - ) -> str: + def product_set_path(project: str,location: str,product_set: str,) -> str: """Returns a fully-qualified product_set string.""" - return ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + return "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) @staticmethod - def parse_product_set_path(path: str) -> Dict[str, str]: + def parse_product_set_path(path: str) -> Dict[str,str]: """Parses a product_set path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def reference_image_path( - project: str, - location: str, - product: str, - reference_image: str, - ) -> str: + def reference_image_path(project: str,location: str,product: str,reference_image: str,) -> str: """Returns a fully-qualified reference_image string.""" - return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( - project=project, - location=location, - product=product, - reference_image=reference_image, - ) + return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format(project=project, location=location, product=product, reference_image=reference_image, ) @staticmethod - def parse_reference_image_path(path: str) -> Dict[str, str]: + def parse_reference_image_path(path: str) -> Dict[str,str]: """Parses a reference_image path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -430,18 +353,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ProductSearchClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -454,9 +373,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -481,9 +398,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -506,9 +421,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ): + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): """Return the API endpoint used by the client. Args: @@ -524,25 +437,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = ProductSearchClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = ProductSearchClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -578,18 +483,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -622,16 +524,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProductSearchTransport, Callable[..., ProductSearchTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the product search client. Args: @@ -686,24 +584,14 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - ( - self._use_client_cert, - self._use_mtls_endpoint, - self._universe_domain_env, - ) = ProductSearchClient._read_environment_variables() - self._client_cert_source = ProductSearchClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = ProductSearchClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) - self._api_endpoint = None # updated below, depending on `transport` + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ProductSearchClient._read_environment_variables() + self._client_cert_source = ProductSearchClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProductSearchClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -714,9 +602,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -725,10 +611,8 @@ def __init__( if transport_provided: # transport is a ProductSearchTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -737,29 +621,20 @@ def __init__( self._transport = cast(ProductSearchTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or ProductSearchClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + ProductSearchClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[ProductSearchTransport], Callable[..., ProductSearchTransport] - ] = ( + transport_init: Union[Type[ProductSearchTransport], Callable[..., ProductSearchTransport]] = ( ProductSearchClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ProductSearchTransport], transport) @@ -778,47 +653,36 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.vision_v1p4beta1.ProductSearchClient`.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "credentialsType": None, - }, + } ) - def create_product_set( - self, - request: Optional[ - Union[product_search_service.CreateProductSetRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product_set: Optional[product_search_service.ProductSet] = None, - product_set_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def create_product_set(self, + request: Optional[Union[product_search_service.CreateProductSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. .. code-block:: python @@ -894,14 +758,10 @@ def sample_create_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product_set, product_set_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -923,7 +783,9 @@ def sample_create_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -940,23 +802,20 @@ def sample_create_product_set(): # Done; return the response. return response - def list_product_sets( - self, - request: Optional[ - Union[product_search_service.ListProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductSetsPager: + def list_product_sets(self, + request: Optional[Union[product_search_service.ListProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductSetsPager: r"""Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. .. code-block:: python @@ -1017,14 +876,10 @@ def sample_list_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1042,7 +897,9 @@ def sample_list_product_sets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1070,22 +927,19 @@ def sample_list_product_sets(): # Done; return the response. return response - def get_product_set( - self, - request: Optional[ - Union[product_search_service.GetProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def get_product_set(self, + request: Optional[Union[product_search_service.GetProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. .. code-block:: python @@ -1146,14 +1000,10 @@ def sample_get_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1171,7 +1021,9 @@ def sample_get_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1188,27 +1040,24 @@ def sample_get_product_set(): # Done; return the response. return response - def update_product_set( - self, - request: Optional[ - Union[product_search_service.UpdateProductSetRequest, dict] - ] = None, - *, - product_set: Optional[product_search_service.ProductSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def update_product_set(self, + request: Optional[Union[product_search_service.UpdateProductSetRequest, dict]] = None, + *, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. .. code-block:: python @@ -1275,14 +1124,10 @@ def sample_update_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product_set, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1302,9 +1147,9 @@ def sample_update_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product_set.name", request.product_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product_set.name", request.product_set.name), + )), ) # Validate the universe domain. @@ -1321,17 +1166,14 @@ def sample_update_product_set(): # Done; return the response. return response - def delete_product_set( - self, - request: Optional[ - Union[product_search_service.DeleteProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_product_set(self, + request: Optional[Union[product_search_service.DeleteProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a ProductSet. Products and ReferenceImages in the ProductSet are not deleted. @@ -1385,14 +1227,10 @@ def sample_delete_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1410,7 +1248,9 @@ def sample_delete_product_set(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1424,29 +1264,26 @@ def sample_delete_product_set(): metadata=metadata, ) - def create_product( - self, - request: Optional[ - Union[product_search_service.CreateProductRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - product: Optional[product_search_service.Product] = None, - product_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def create_product(self, + request: Optional[Union[product_search_service.CreateProductRequest, dict]] = None, + *, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. .. code-block:: python @@ -1517,14 +1354,10 @@ def sample_create_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, product, product_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1546,7 +1379,9 @@ def sample_create_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1563,23 +1398,20 @@ def sample_create_product(): # Done; return the response. return response - def list_products( - self, - request: Optional[ - Union[product_search_service.ListProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsPager: + def list_products(self, + request: Optional[Union[product_search_service.ListProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsPager: r"""Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -1640,14 +1472,10 @@ def sample_list_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1665,7 +1493,9 @@ def sample_list_products(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -1693,20 +1523,19 @@ def sample_list_products(): # Done; return the response. return response - def get_product( - self, - request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def get_product(self, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. .. code-block:: python @@ -1762,14 +1591,10 @@ def sample_get_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1787,7 +1612,9 @@ def sample_get_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1804,18 +1631,15 @@ def sample_get_product(): # Done; return the response. return response - def update_product( - self, - request: Optional[ - Union[product_search_service.UpdateProductRequest, dict] - ] = None, - *, - product: Optional[product_search_service.Product] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def update_product(self, + request: Optional[Union[product_search_service.UpdateProductRequest, dict]] = None, + *, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, ``description``, and ``labels`` fields can be updated right now. @@ -1824,14 +1648,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. .. code-block:: python @@ -1895,14 +1719,10 @@ def sample_update_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [product, update_mask] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1922,9 +1742,9 @@ def sample_update_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("product.name", request.product.name),) - ), + gapic_v1.routing_header.to_grpc_metadata(( + ("product.name", request.product.name), + )), ) # Validate the universe domain. @@ -1941,17 +1761,14 @@ def sample_update_product(): # Done; return the response. return response - def delete_product( - self, - request: Optional[ - Union[product_search_service.DeleteProductRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_product(self, + request: Optional[Union[product_search_service.DeleteProductRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a product and its reference images. Metadata of the product and all its images will be @@ -2006,14 +1823,10 @@ def sample_delete_product(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2031,7 +1844,9 @@ def sample_delete_product(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2045,19 +1860,16 @@ def sample_delete_product(): metadata=metadata, ) - def create_reference_image( - self, - request: Optional[ - Union[product_search_service.CreateReferenceImageRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - reference_image: Optional[product_search_service.ReferenceImage] = None, - reference_image_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def create_reference_image(self, + request: Optional[Union[product_search_service.CreateReferenceImageRequest, dict]] = None, + *, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. The ``bounding_poly`` field is optional. If ``bounding_poly`` is @@ -2072,14 +1884,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. .. code-block:: python @@ -2160,14 +1972,10 @@ def sample_create_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, reference_image, reference_image_id] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2189,7 +1997,9 @@ def sample_create_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2206,17 +2016,14 @@ def sample_create_reference_image(): # Done; return the response. return response - def delete_reference_image( - self, - request: Optional[ - Union[product_search_service.DeleteReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_reference_image(self, + request: Optional[Union[product_search_service.DeleteReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Permanently deletes a reference image. The image metadata will be deleted right away, but @@ -2275,14 +2082,10 @@ def sample_delete_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2300,7 +2103,9 @@ def sample_delete_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2314,24 +2119,21 @@ def sample_delete_reference_image(): metadata=metadata, ) - def list_reference_images( - self, - request: Optional[ - Union[product_search_service.ListReferenceImagesRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListReferenceImagesPager: + def list_reference_images(self, + request: Optional[Union[product_search_service.ListReferenceImagesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListReferenceImagesPager: r"""Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. .. code-block:: python @@ -2393,14 +2195,10 @@ def sample_list_reference_images(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2418,7 +2216,9 @@ def sample_list_reference_images(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -2446,22 +2246,19 @@ def sample_list_reference_images(): # Done; return the response. return response - def get_reference_image( - self, - request: Optional[ - Union[product_search_service.GetReferenceImageRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def get_reference_image(self, + request: Optional[Union[product_search_service.GetReferenceImageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. .. code-block:: python @@ -2521,14 +2318,10 @@ def sample_get_reference_image(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2546,7 +2339,9 @@ def sample_get_reference_image(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2563,18 +2358,15 @@ def sample_get_reference_image(): # Done; return the response. return response - def add_product_to_product_set( - self, - request: Optional[ - Union[product_search_service.AddProductToProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def add_product_to_product_set(self, + request: Optional[Union[product_search_service.AddProductToProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is already present, no change is made. @@ -2582,8 +2374,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. .. code-block:: python @@ -2645,20 +2437,14 @@ def sample_add_product_to_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.AddProductToProductSetRequest - ): + if not isinstance(request, product_search_service.AddProductToProductSetRequest): request = product_search_service.AddProductToProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2669,14 +2455,14 @@ def sample_add_product_to_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.add_product_to_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.add_product_to_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2690,18 +2476,15 @@ def sample_add_product_to_product_set(): metadata=metadata, ) - def remove_product_from_product_set( - self, - request: Optional[ - Union[product_search_service.RemoveProductFromProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - product: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def remove_product_from_product_set(self, + request: Optional[Union[product_search_service.RemoveProductFromProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + product: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Removes a Product from the specified ProductSet. .. code-block:: python @@ -2764,20 +2547,14 @@ def sample_remove_product_from_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, product] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.RemoveProductFromProductSetRequest - ): + if not isinstance(request, product_search_service.RemoveProductFromProductSetRequest): request = product_search_service.RemoveProductFromProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2788,14 +2565,14 @@ def sample_remove_product_from_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.remove_product_from_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.remove_product_from_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2809,25 +2586,22 @@ def sample_remove_product_from_product_set(): metadata=metadata, ) - def list_products_in_product_set( - self, - request: Optional[ - Union[product_search_service.ListProductsInProductSetRequest, dict] - ] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProductsInProductSetPager: + def list_products_in_product_set(self, + request: Optional[Union[product_search_service.ListProductsInProductSetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProductsInProductSetPager: r"""Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. .. code-block:: python @@ -2891,20 +2665,14 @@ def sample_list_products_in_product_set(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, product_search_service.ListProductsInProductSetRequest - ): + if not isinstance(request, product_search_service.ListProductsInProductSetRequest): request = product_search_service.ListProductsInProductSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -2913,14 +2681,14 @@ def sample_list_products_in_product_set(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_products_in_product_set - ] + rpc = self._transport._wrapped_methods[self._transport.list_products_in_product_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -2948,20 +2716,15 @@ def sample_list_products_in_product_set(): # Done; return the response. return response - def import_product_sets( - self, - request: Optional[ - Union[product_search_service.ImportProductSetsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - input_config: Optional[ - product_search_service.ImportProductSetsInputConfig - ] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def import_product_sets(self, + request: Optional[Union[product_search_service.ImportProductSetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + input_config: Optional[product_search_service.ImportProductSetsInputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. @@ -3051,14 +2814,10 @@ def sample_import_product_sets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, input_config] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3078,7 +2837,9 @@ def sample_import_product_sets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3103,17 +2864,14 @@ def sample_import_product_sets(): # Done; return the response. return response - def purge_products( - self, - request: Optional[ - Union[product_search_service.PurgeProductsRequest, dict] - ] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def purge_products(self, + request: Optional[Union[product_search_service.PurgeProductsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronous API to delete all Products in a ProductSet or all Products that are in no ProductSet. @@ -3212,14 +2970,10 @@ def sample_purge_products(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3237,7 +2991,9 @@ def sample_purge_products(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), ) # Validate the universe domain. @@ -3276,11 +3032,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("ProductSearchClient",) +__all__ = ( + "ProductSearchClient", +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/pagers.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/pagers.py index 8000978f3121..7a0afcc1848e 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/pagers.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/pagers.py @@ -13,27 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import ( - Any, - AsyncIterator, - Awaitable, - Callable, - Iterator, - Optional, - Sequence, - Tuple, - Union, -) - from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import retry_async as retries_async - +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[ - retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None - ] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore @@ -58,17 +44,14 @@ class ListProductSetsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductSetsResponse], - request: product_search_service.ListProductSetsRequest, - response: product_search_service.ListProductSetsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductSetsResponse], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -101,12 +84,7 @@ def pages(self) -> Iterator[product_search_service.ListProductSetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.ProductSet]: @@ -114,7 +92,7 @@ def __iter__(self) -> Iterator[product_search_service.ProductSet]: yield from page.product_sets def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductSetsAsyncPager: @@ -134,19 +112,14 @@ class ListProductSetsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListProductSetsResponse] - ], - request: product_search_service.ListProductSetsRequest, - response: product_search_service.ListProductSetsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductSetsResponse]], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -175,20 +148,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListProductSetsResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListProductSetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.ProductSet]: async def async_generator(): async for page in self.pages: @@ -198,7 +163,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsPager: @@ -218,17 +183,14 @@ class ListProductsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductsResponse], - request: product_search_service.ListProductsRequest, - response: product_search_service.ListProductsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductsResponse], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -261,12 +223,7 @@ def pages(self) -> Iterator[product_search_service.ListProductsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.Product]: @@ -274,7 +231,7 @@ def __iter__(self) -> Iterator[product_search_service.Product]: yield from page.products def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsAsyncPager: @@ -294,17 +251,14 @@ class ListProductsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], - request: product_search_service.ListProductsRequest, - response: product_search_service.ListProductsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -337,14 +291,8 @@ async def pages(self) -> AsyncIterator[product_search_service.ListProductsRespon yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.Product]: async def async_generator(): async for page in self.pages: @@ -354,7 +302,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListReferenceImagesPager: @@ -374,17 +322,14 @@ class ListReferenceImagesPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListReferenceImagesResponse], - request: product_search_service.ListReferenceImagesRequest, - response: product_search_service.ListReferenceImagesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListReferenceImagesResponse], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -417,12 +362,7 @@ def pages(self) -> Iterator[product_search_service.ListReferenceImagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.ReferenceImage]: @@ -430,7 +370,7 @@ def __iter__(self) -> Iterator[product_search_service.ReferenceImage]: yield from page.reference_images def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListReferenceImagesAsyncPager: @@ -450,19 +390,14 @@ class ListReferenceImagesAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListReferenceImagesResponse] - ], - request: product_search_service.ListReferenceImagesRequest, - response: product_search_service.ListReferenceImagesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListReferenceImagesResponse]], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -491,20 +426,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListReferenceImagesResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListReferenceImagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.ReferenceImage]: async def async_generator(): async for page in self.pages: @@ -514,7 +441,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsInProductSetPager: @@ -534,17 +461,14 @@ class ListProductsInProductSetPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[..., product_search_service.ListProductsInProductSetResponse], - request: product_search_service.ListProductsInProductSetRequest, - response: product_search_service.ListProductsInProductSetResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., product_search_service.ListProductsInProductSetResponse], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiate the pager. Args: @@ -573,18 +497,11 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages( - self, - ) -> Iterator[product_search_service.ListProductsInProductSetResponse]: + def pages(self) -> Iterator[product_search_service.ListProductsInProductSetResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[product_search_service.Product]: @@ -592,7 +509,7 @@ def __iter__(self) -> Iterator[product_search_service.Product]: yield from page.products def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListProductsInProductSetAsyncPager: @@ -612,19 +529,14 @@ class ListProductsInProductSetAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[product_search_service.ListProductsInProductSetResponse] - ], - request: product_search_service.ListProductsInProductSetRequest, - response: product_search_service.ListProductsInProductSetResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = () - ): + def __init__(self, + method: Callable[..., Awaitable[product_search_service.ListProductsInProductSetResponse]], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): """Instantiates the pager. Args: @@ -653,20 +565,12 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages( - self, - ) -> AsyncIterator[product_search_service.ListProductsInProductSetResponse]: + async def pages(self) -> AsyncIterator[product_search_service.ListProductsInProductSetResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = await self._method( - self._request, - retry=self._retry, - timeout=self._timeout, - metadata=self._metadata, - ) + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterator[product_search_service.Product]: async def async_generator(): async for page in self.pages: @@ -676,4 +580,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py index e3bd7adc48d8..f5f6aac78c26 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py @@ -19,18 +19,20 @@ from .base import ProductSearchTransport from .grpc import ProductSearchGrpcTransport from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport -from .rest import ProductSearchRestInterceptor, ProductSearchRestTransport +from .rest import ProductSearchRestTransport +from .rest import ProductSearchRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] -_transport_registry["grpc"] = ProductSearchGrpcTransport -_transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport -_transport_registry["rest"] = ProductSearchRestTransport +_transport_registry['grpc'] = ProductSearchGrpcTransport +_transport_registry['grpc_asyncio'] = ProductSearchGrpcAsyncIOTransport +_transport_registry['rest'] = ProductSearchRestTransport __all__ = ( - "ProductSearchTransport", - "ProductSearchGrpcTransport", - "ProductSearchGrpcAsyncIOTransport", - "ProductSearchRestTransport", - "ProductSearchRestInterceptor", + 'ProductSearchTransport', + 'ProductSearchGrpcTransport', + 'ProductSearchGrpcAsyncIOTransport', + 'ProductSearchRestTransport', + 'ProductSearchRestInterceptor', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py index 64ce1bc97cbd..3477f6baaa59 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py @@ -16,23 +16,23 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +from google.cloud.vision_v1p4beta1 import gapic_version as package_version + +import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, operations_v1 +from google.api_core import gapic_v1 from google.api_core import retry as retries -import google.auth # type: ignore +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.protobuf import empty_pb2 # type: ignore -from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.cloud.vision_v1p4beta1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -42,25 +42,24 @@ class ProductSearchTransport(abc.ABC): """Abstract transport class for ProductSearch.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', ) - DEFAULT_HOST: str = "vision.googleapis.com" + DEFAULT_HOST: str = 'vision.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -87,8 +86,6 @@ def __init__( be used for service account credentials. """ - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - # Save the scopes. self._scopes = scopes if not hasattr(self, "_ignore_credentials"): @@ -97,38 +94,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - **scopes_kwargs, quota_project_id=quota_project_id - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host @property @@ -144,7 +134,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -186,7 +177,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -213,7 +205,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -255,7 +248,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -282,7 +276,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -339,7 +334,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -351,7 +347,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -378,7 +375,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -389,14 +387,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -406,207 +404,174 @@ def operations_client(self): raise NotImplementedError() @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - Union[ - product_search_service.ListProductSetsResponse, - Awaitable[product_search_service.ListProductSetsResponse], - ], - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + Union[ + product_search_service.ListProductSetsResponse, + Awaitable[product_search_service.ListProductSetsResponse] + ]]: raise NotImplementedError() @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - Union[ - product_search_service.ProductSet, - Awaitable[product_search_service.ProductSet], - ], - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Union[ + product_search_service.ProductSet, + Awaitable[product_search_service.ProductSet] + ]]: raise NotImplementedError() @property - def delete_product_set( - self, - ) -> Callable[ - [product_search_service.DeleteProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - Union[ - product_search_service.ListProductsResponse, - Awaitable[product_search_service.ListProductsResponse], - ], - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + Union[ + product_search_service.ListProductsResponse, + Awaitable[product_search_service.ListProductsResponse] + ]]: raise NotImplementedError() @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], - Union[ - product_search_service.Product, Awaitable[product_search_service.Product] - ], - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + Union[ + product_search_service.Product, + Awaitable[product_search_service.Product] + ]]: raise NotImplementedError() @property - def delete_product( - self, - ) -> Callable[ - [product_search_service.DeleteProductRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - Union[ - product_search_service.ReferenceImage, - Awaitable[product_search_service.ReferenceImage], - ], - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Union[ + product_search_service.ReferenceImage, + Awaitable[product_search_service.ReferenceImage] + ]]: raise NotImplementedError() @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - Union[ - product_search_service.ListReferenceImagesResponse, - Awaitable[product_search_service.ListReferenceImagesResponse], - ], - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Union[ + product_search_service.ListReferenceImagesResponse, + Awaitable[product_search_service.ListReferenceImagesResponse] + ]]: raise NotImplementedError() @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - Union[ - product_search_service.ReferenceImage, - Awaitable[product_search_service.ReferenceImage], - ], - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Union[ + product_search_service.ReferenceImage, + Awaitable[product_search_service.ReferenceImage] + ]]: raise NotImplementedError() @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], - Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: raise NotImplementedError() @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - Union[ - product_search_service.ListProductsInProductSetResponse, - Awaitable[product_search_service.ListProductsInProductSetResponse], - ], - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Union[ + product_search_service.ListProductsInProductSetResponse, + Awaitable[product_search_service.ListProductsInProductSetResponse] + ]]: raise NotImplementedError() @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: raise NotImplementedError() @property @@ -614,4 +579,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("ProductSearchTransport",) +__all__ = ( + 'ProductSearchTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py index 452d930a604c..e9edfda1f986 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py @@ -16,27 +16,28 @@ import json import logging as std_logging import pickle -from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, grpc_helpers, operations_v1 -import google.auth # type: ignore +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message + import grpc # type: ignore import proto # type: ignore from google.cloud.vision_v1p4beta1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +47,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +68,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,11 +79,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -99,7 +94,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,22 +110,23 @@ class ProductSearchGrpcTransport(ProductSearchTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -139,26 +135,23 @@ class ProductSearchGrpcTransport(ProductSearchTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -282,23 +275,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -334,12 +323,13 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property @@ -359,20 +349,17 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - product_search_service.ProductSet, - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the create product set method over gRPC. Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. Returns: Callable[[~.CreateProductSetRequest], @@ -384,29 +371,26 @@ def create_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product_set" not in self._stubs: - self._stubs["create_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet", + if 'create_product_set' not in self._stubs: + self._stubs['create_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet', request_serializer=product_search_service.CreateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["create_product_set"] + return self._stubs['create_product_set'] @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - product_search_service.ListProductSetsResponse, - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse]: r"""Return a callable for the list product sets method over gRPC. Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. Returns: Callable[[~.ListProductSetsRequest], @@ -418,27 +402,25 @@ def list_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_product_sets" not in self._stubs: - self._stubs["list_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets", + if 'list_product_sets' not in self._stubs: + self._stubs['list_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets', request_serializer=product_search_service.ListProductSetsRequest.serialize, response_deserializer=product_search_service.ListProductSetsResponse.deserialize, ) - return self._stubs["list_product_sets"] + return self._stubs['list_product_sets'] @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], product_search_service.ProductSet - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the get product set method over gRPC. Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.GetProductSetRequest], @@ -450,21 +432,18 @@ def get_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product_set" not in self._stubs: - self._stubs["get_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet", + if 'get_product_set' not in self._stubs: + self._stubs['get_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet', request_serializer=product_search_service.GetProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["get_product_set"] + return self._stubs['get_product_set'] @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - product_search_service.ProductSet, - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet]: r"""Return a callable for the update product set method over gRPC. Makes changes to a ProductSet resource. Only display_name can be @@ -472,10 +451,10 @@ def update_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. Returns: Callable[[~.UpdateProductSetRequest], @@ -487,18 +466,18 @@ def update_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product_set" not in self._stubs: - self._stubs["update_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet", + if 'update_product_set' not in self._stubs: + self._stubs['update_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet', request_serializer=product_search_service.UpdateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["update_product_set"] + return self._stubs['update_product_set'] @property - def delete_product_set( - self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. Products and @@ -517,32 +496,30 @@ def delete_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product_set" not in self._stubs: - self._stubs["delete_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet", + if 'delete_product_set' not in self._stubs: + self._stubs['delete_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet', request_serializer=product_search_service.DeleteProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product_set"] + return self._stubs['delete_product_set'] @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], product_search_service.Product - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + product_search_service.Product]: r"""Return a callable for the create product method over gRPC. Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. Returns: Callable[[~.CreateProductRequest], @@ -554,29 +531,26 @@ def create_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product" not in self._stubs: - self._stubs["create_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct", + if 'create_product' not in self._stubs: + self._stubs['create_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct', request_serializer=product_search_service.CreateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["create_product"] + return self._stubs['create_product'] @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - product_search_service.ListProductsResponse, - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse]: r"""Return a callable for the list products method over gRPC. Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsRequest], @@ -588,27 +562,25 @@ def list_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products" not in self._stubs: - self._stubs["list_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts", + if 'list_products' not in self._stubs: + self._stubs['list_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts', request_serializer=product_search_service.ListProductsRequest.serialize, response_deserializer=product_search_service.ListProductsResponse.deserialize, ) - return self._stubs["list_products"] + return self._stubs['list_products'] @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], product_search_service.Product - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + product_search_service.Product]: r"""Return a callable for the get product method over gRPC. Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. Returns: Callable[[~.GetProductRequest], @@ -620,20 +592,18 @@ def get_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product" not in self._stubs: - self._stubs["get_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct", + if 'get_product' not in self._stubs: + self._stubs['get_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct', request_serializer=product_search_service.GetProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["get_product"] + return self._stubs['get_product'] @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], product_search_service.Product - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + product_search_service.Product]: r"""Return a callable for the update product method over gRPC. Makes changes to a Product resource. Only the ``display_name``, @@ -644,14 +614,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. Returns: Callable[[~.UpdateProductRequest], @@ -663,18 +633,18 @@ def update_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product" not in self._stubs: - self._stubs["update_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct", + if 'update_product' not in self._stubs: + self._stubs['update_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct', request_serializer=product_search_service.UpdateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["update_product"] + return self._stubs['update_product'] @property - def delete_product( - self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + empty_pb2.Empty]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference @@ -694,21 +664,18 @@ def delete_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product" not in self._stubs: - self._stubs["delete_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct", + if 'delete_product' not in self._stubs: + self._stubs['delete_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct', request_serializer=product_search_service.DeleteProductRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product"] + return self._stubs['delete_product'] @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage]: r"""Return a callable for the create reference image method over gRPC. Creates and returns a new ReferenceImage resource. @@ -725,14 +692,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. Returns: Callable[[~.CreateReferenceImageRequest], @@ -744,20 +711,18 @@ def create_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_reference_image" not in self._stubs: - self._stubs["create_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage", + if 'create_reference_image' not in self._stubs: + self._stubs['create_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage', request_serializer=product_search_service.CreateReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["create_reference_image"] + return self._stubs['create_reference_image'] @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + empty_pb2.Empty]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -779,30 +744,27 @@ def delete_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_reference_image" not in self._stubs: - self._stubs["delete_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage", + if 'delete_reference_image' not in self._stubs: + self._stubs['delete_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage', request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_reference_image"] + return self._stubs['delete_reference_image'] @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - product_search_service.ListReferenceImagesResponse, - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse]: r"""Return a callable for the list reference images method over gRPC. Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. Returns: Callable[[~.ListReferenceImagesRequest], @@ -814,28 +776,25 @@ def list_reference_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_reference_images" not in self._stubs: - self._stubs["list_reference_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages", + if 'list_reference_images' not in self._stubs: + self._stubs['list_reference_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages', request_serializer=product_search_service.ListReferenceImagesRequest.serialize, response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, ) - return self._stubs["list_reference_images"] + return self._stubs['list_reference_images'] @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage]: r"""Return a callable for the get reference image method over gRPC. Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. Returns: Callable[[~.GetReferenceImageRequest], @@ -847,20 +806,18 @@ def get_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_reference_image" not in self._stubs: - self._stubs["get_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage", + if 'get_reference_image' not in self._stubs: + self._stubs['get_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage', request_serializer=product_search_service.GetReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["get_reference_image"] + return self._stubs['get_reference_image'] @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], empty_pb2.Empty - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the add product to product set method over gRPC. Adds a Product to the specified ProductSet. If the Product is @@ -870,8 +827,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. Returns: Callable[[~.AddProductToProductSetRequest], @@ -883,22 +840,18 @@ def add_product_to_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "add_product_to_product_set" not in self._stubs: - self._stubs[ - "add_product_to_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet", + if 'add_product_to_product_set' not in self._stubs: + self._stubs['add_product_to_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet', request_serializer=product_search_service.AddProductToProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["add_product_to_product_set"] + return self._stubs['add_product_to_product_set'] @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + empty_pb2.Empty]: r"""Return a callable for the remove product from product set method over gRPC. @@ -914,23 +867,18 @@ def remove_product_from_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "remove_product_from_product_set" not in self._stubs: - self._stubs[ - "remove_product_from_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet", + if 'remove_product_from_product_set' not in self._stubs: + self._stubs['remove_product_from_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet', request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["remove_product_from_product_set"] + return self._stubs['remove_product_from_product_set'] @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - product_search_service.ListProductsInProductSetResponse, - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse]: r"""Return a callable for the list products in product set method over gRPC. Lists the Products in a ProductSet, in an unspecified order. If @@ -939,8 +887,8 @@ def list_products_in_product_set( Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsInProductSetRequest], @@ -952,22 +900,18 @@ def list_products_in_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products_in_product_set" not in self._stubs: - self._stubs[ - "list_products_in_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet", + if 'list_products_in_product_set' not in self._stubs: + self._stubs['list_products_in_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet', request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, ) - return self._stubs["list_products_in_product_set"] + return self._stubs['list_products_in_product_set'] @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations_pb2.Operation - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + operations_pb2.Operation]: r"""Return a callable for the import product sets method over gRPC. Asynchronous API that imports a list of reference images to @@ -993,20 +937,18 @@ def import_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_product_sets" not in self._stubs: - self._stubs["import_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets", + if 'import_product_sets' not in self._stubs: + self._stubs['import_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets', request_serializer=product_search_service.ImportProductSetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_product_sets"] + return self._stubs['import_product_sets'] @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], operations_pb2.Operation - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + operations_pb2.Operation]: r"""Return a callable for the purge products method over gRPC. Asynchronous API to delete all Products in a ProductSet or all @@ -1047,13 +989,13 @@ def purge_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "purge_products" not in self._stubs: - self._stubs["purge_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts", + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts', request_serializer=product_search_service.PurgeProductsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["purge_products"] + return self._stubs['purge_products'] def close(self): self._logged_channel.close() @@ -1063,4 +1005,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("ProductSearchGrpcTransport",) +__all__ = ( + 'ProductSearchGrpcTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py index 16ae1eac3171..e9e7d4ee87ed 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py @@ -15,32 +15,33 @@ # import inspect import json -import logging as std_logging import pickle -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import logging as std_logging import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message -import grpc # type: ignore + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore -import proto # type: ignore from google.cloud.vision_v1p4beta1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .grpc import ProductSearchGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -48,13 +49,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -75,7 +72,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -86,11 +83,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -105,7 +98,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -121,22 +114,23 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -150,15 +144,13 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -189,26 +181,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -334,9 +324,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -367,20 +355,17 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the create product set method over gRPC. Creates and returns a new ProductSet resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing, or is - longer than 4096 characters. + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. Returns: Callable[[~.CreateProductSetRequest], @@ -392,29 +377,26 @@ def create_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product_set" not in self._stubs: - self._stubs["create_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet", + if 'create_product_set' not in self._stubs: + self._stubs['create_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet', request_serializer=product_search_service.CreateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["create_product_set"] + return self._stubs['create_product_set'] @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - Awaitable[product_search_service.ListProductSetsResponse], - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + Awaitable[product_search_service.ListProductSetsResponse]]: r"""Return a callable for the list product sets method over gRPC. Lists ProductSets in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100, or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. Returns: Callable[[~.ListProductSetsRequest], @@ -426,28 +408,25 @@ def list_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_product_sets" not in self._stubs: - self._stubs["list_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets", + if 'list_product_sets' not in self._stubs: + self._stubs['list_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets', request_serializer=product_search_service.ListProductSetsRequest.serialize, response_deserializer=product_search_service.ListProductSetsResponse.deserialize, ) - return self._stubs["list_product_sets"] + return self._stubs['list_product_sets'] @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the get product set method over gRPC. Gets information associated with a ProductSet. Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. + - Returns NOT_FOUND if the ProductSet does not exist. Returns: Callable[[~.GetProductSetRequest], @@ -459,21 +438,18 @@ def get_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product_set" not in self._stubs: - self._stubs["get_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet", + if 'get_product_set' not in self._stubs: + self._stubs['get_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet', request_serializer=product_search_service.GetProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["get_product_set"] + return self._stubs['get_product_set'] @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - Awaitable[product_search_service.ProductSet], - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Awaitable[product_search_service.ProductSet]]: r"""Return a callable for the update product set method over gRPC. Makes changes to a ProductSet resource. Only display_name can be @@ -481,10 +457,10 @@ def update_product_set( Possible errors: - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but missing from the request or longer than 4096 - characters. + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. Returns: Callable[[~.UpdateProductSetRequest], @@ -496,20 +472,18 @@ def update_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product_set" not in self._stubs: - self._stubs["update_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet", + if 'update_product_set' not in self._stubs: + self._stubs['update_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet', request_serializer=product_search_service.UpdateProductSetRequest.serialize, response_deserializer=product_search_service.ProductSet.deserialize, ) - return self._stubs["update_product_set"] + return self._stubs['update_product_set'] @property - def delete_product_set( - self, - ) -> Callable[ - [product_search_service.DeleteProductSetRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. Products and @@ -528,33 +502,30 @@ def delete_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product_set" not in self._stubs: - self._stubs["delete_product_set"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet", + if 'delete_product_set' not in self._stubs: + self._stubs['delete_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet', request_serializer=product_search_service.DeleteProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product_set"] + return self._stubs['delete_product_set'] @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], - Awaitable[product_search_service.Product], - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the create product method over gRPC. Creates and returns a new product resource. Possible errors: - - Returns INVALID_ARGUMENT if display_name is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or - invalid. + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. Returns: Callable[[~.CreateProductRequest], @@ -566,29 +537,26 @@ def create_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_product" not in self._stubs: - self._stubs["create_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct", + if 'create_product' not in self._stubs: + self._stubs['create_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct', request_serializer=product_search_service.CreateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["create_product"] + return self._stubs['create_product'] @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - Awaitable[product_search_service.ListProductsResponse], - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + Awaitable[product_search_service.ListProductsResponse]]: r"""Return a callable for the list products method over gRPC. Lists products in an unspecified order. Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsRequest], @@ -600,28 +568,25 @@ def list_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products" not in self._stubs: - self._stubs["list_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts", + if 'list_products' not in self._stubs: + self._stubs['list_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts', request_serializer=product_search_service.ListProductsRequest.serialize, response_deserializer=product_search_service.ListProductsResponse.deserialize, ) - return self._stubs["list_products"] + return self._stubs['list_products'] @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], - Awaitable[product_search_service.Product], - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the get product method over gRPC. Gets information associated with a Product. Possible errors: - - Returns NOT_FOUND if the Product does not exist. + - Returns NOT_FOUND if the Product does not exist. Returns: Callable[[~.GetProductRequest], @@ -633,21 +598,18 @@ def get_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_product" not in self._stubs: - self._stubs["get_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct", + if 'get_product' not in self._stubs: + self._stubs['get_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct', request_serializer=product_search_service.GetProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["get_product"] + return self._stubs['get_product'] @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], - Awaitable[product_search_service.Product], - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + Awaitable[product_search_service.Product]]: r"""Return a callable for the update product method over gRPC. Makes changes to a Product resource. Only the ``display_name``, @@ -658,14 +620,14 @@ def update_product( Possible errors: - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in - update_mask but is missing from the request or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is present in - update_mask but is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. Returns: Callable[[~.UpdateProductRequest], @@ -677,20 +639,18 @@ def update_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "update_product" not in self._stubs: - self._stubs["update_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct", + if 'update_product' not in self._stubs: + self._stubs['update_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct', request_serializer=product_search_service.UpdateProductRequest.serialize, response_deserializer=product_search_service.Product.deserialize, ) - return self._stubs["update_product"] + return self._stubs['update_product'] @property - def delete_product( - self, - ) -> Callable[ - [product_search_service.DeleteProductRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference @@ -710,21 +670,18 @@ def delete_product( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_product" not in self._stubs: - self._stubs["delete_product"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct", + if 'delete_product' not in self._stubs: + self._stubs['delete_product'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct', request_serializer=product_search_service.DeleteProductRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_product"] + return self._stubs['delete_product'] @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - Awaitable[product_search_service.ReferenceImage], - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage]]: r"""Return a callable for the create reference image method over gRPC. Creates and returns a new ReferenceImage resource. @@ -741,14 +698,14 @@ def create_reference_image( Possible errors: - - Returns INVALID_ARGUMENT if the image_uri is missing or longer - than 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category - is detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than - 10 polygons. + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. Returns: Callable[[~.CreateReferenceImageRequest], @@ -760,20 +717,18 @@ def create_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_reference_image" not in self._stubs: - self._stubs["create_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage", + if 'create_reference_image' not in self._stubs: + self._stubs['create_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage', request_serializer=product_search_service.CreateReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["create_reference_image"] + return self._stubs['create_reference_image'] @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], Awaitable[empty_pb2.Empty] - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -795,30 +750,27 @@ def delete_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_reference_image" not in self._stubs: - self._stubs["delete_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage", + if 'delete_reference_image' not in self._stubs: + self._stubs['delete_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage', request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["delete_reference_image"] + return self._stubs['delete_reference_image'] @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - Awaitable[product_search_service.ListReferenceImagesResponse], - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Awaitable[product_search_service.ListReferenceImagesResponse]]: r"""Return a callable for the list reference images method over gRPC. Lists reference images. Possible errors: - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, - or less than 1. + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. Returns: Callable[[~.ListReferenceImagesRequest], @@ -830,28 +782,25 @@ def list_reference_images( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_reference_images" not in self._stubs: - self._stubs["list_reference_images"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages", + if 'list_reference_images' not in self._stubs: + self._stubs['list_reference_images'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages', request_serializer=product_search_service.ListReferenceImagesRequest.serialize, response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, ) - return self._stubs["list_reference_images"] + return self._stubs['list_reference_images'] @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - Awaitable[product_search_service.ReferenceImage], - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage]]: r"""Return a callable for the get reference image method over gRPC. Gets information associated with a ReferenceImage. Possible errors: - - Returns NOT_FOUND if the specified image does not exist. + - Returns NOT_FOUND if the specified image does not exist. Returns: Callable[[~.GetReferenceImageRequest], @@ -863,21 +812,18 @@ def get_reference_image( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_reference_image" not in self._stubs: - self._stubs["get_reference_image"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage", + if 'get_reference_image' not in self._stubs: + self._stubs['get_reference_image'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage', request_serializer=product_search_service.GetReferenceImageRequest.serialize, response_deserializer=product_search_service.ReferenceImage.deserialize, ) - return self._stubs["get_reference_image"] + return self._stubs['get_reference_image'] @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], - Awaitable[empty_pb2.Empty], - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the add product to product set method over gRPC. Adds a Product to the specified ProductSet. If the Product is @@ -887,8 +833,8 @@ def add_product_to_product_set( Possible errors: - - Returns NOT_FOUND if the Product or the ProductSet doesn't - exist. + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. Returns: Callable[[~.AddProductToProductSetRequest], @@ -900,23 +846,18 @@ def add_product_to_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "add_product_to_product_set" not in self._stubs: - self._stubs[ - "add_product_to_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet", + if 'add_product_to_product_set' not in self._stubs: + self._stubs['add_product_to_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet', request_serializer=product_search_service.AddProductToProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["add_product_to_product_set"] + return self._stubs['add_product_to_product_set'] @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], - Awaitable[empty_pb2.Empty], - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Awaitable[empty_pb2.Empty]]: r"""Return a callable for the remove product from product set method over gRPC. @@ -932,23 +873,18 @@ def remove_product_from_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "remove_product_from_product_set" not in self._stubs: - self._stubs[ - "remove_product_from_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet", + if 'remove_product_from_product_set' not in self._stubs: + self._stubs['remove_product_from_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet', request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs["remove_product_from_product_set"] + return self._stubs['remove_product_from_product_set'] @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - Awaitable[product_search_service.ListProductsInProductSetResponse], - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Awaitable[product_search_service.ListProductsInProductSetResponse]]: r"""Return a callable for the list products in product set method over gRPC. Lists the Products in a ProductSet, in an unspecified order. If @@ -957,8 +893,8 @@ def list_products_in_product_set( Possible errors: - - Returns INVALID_ARGUMENT if page_size is greater than 100 or - less than 1. + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. Returns: Callable[[~.ListProductsInProductSetRequest], @@ -970,23 +906,18 @@ def list_products_in_product_set( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_products_in_product_set" not in self._stubs: - self._stubs[ - "list_products_in_product_set" - ] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet", + if 'list_products_in_product_set' not in self._stubs: + self._stubs['list_products_in_product_set'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet', request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, ) - return self._stubs["list_products_in_product_set"] + return self._stubs['list_products_in_product_set'] @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], - Awaitable[operations_pb2.Operation], - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import product sets method over gRPC. Asynchronous API that imports a list of reference images to @@ -1012,21 +943,18 @@ def import_product_sets( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "import_product_sets" not in self._stubs: - self._stubs["import_product_sets"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets", + if 'import_product_sets' not in self._stubs: + self._stubs['import_product_sets'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets', request_serializer=product_search_service.ImportProductSetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["import_product_sets"] + return self._stubs['import_product_sets'] @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], - Awaitable[operations_pb2.Operation], - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + Awaitable[operations_pb2.Operation]]: r"""Return a callable for the purge products method over gRPC. Asynchronous API to delete all Products in a ProductSet or all @@ -1067,16 +995,16 @@ def purge_products( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "purge_products" not in self._stubs: - self._stubs["purge_products"] = self._logged_channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts", + if 'purge_products' not in self._stubs: + self._stubs['purge_products'] = self._logged_channel.unary_unary( + '/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts', request_serializer=product_search_service.PurgeProductsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs["purge_products"] + return self._stubs['purge_products'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.create_product_set: self._wrap_method( self.create_product_set, @@ -1084,7 +1012,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1126,7 +1055,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1153,7 +1083,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1195,7 +1126,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1222,7 +1154,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1279,7 +1212,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1291,7 +1225,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1318,7 +1253,8 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(), + predicate=retries.if_exception_type( + ), deadline=600.0, ), default_timeout=600.0, @@ -1344,4 +1280,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("ProductSearchGrpcAsyncIOTransport",) +__all__ = ( + 'ProductSearchGrpcAsyncIOTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest.py index af54bbc62247..1aed028974bb 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest.py @@ -13,27 +13,34 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings +import json # type: ignore -from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.auth.transport.requests import AuthorizedSession # 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.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 import google.protobuf -from google.protobuf import empty_pb2 # type: ignore + from google.protobuf import json_format +from google.api_core import operations_v1 + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.cloud.vision_v1p4beta1.types import product_search_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseProductSearchRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,7 +49,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -211,15 +217,7 @@ def post_update_product_set(self, response): """ - - def pre_add_product_to_product_set( - self, - request: product_search_service.AddProductToProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.AddProductToProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_add_product_to_product_set(self, request: product_search_service.AddProductToProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.AddProductToProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for add_product_to_product_set Override in a subclass to manipulate the request or metadata @@ -227,14 +225,7 @@ def pre_add_product_to_product_set( """ return request, metadata - def pre_create_product( - self, - request: product_search_service.CreateProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_product(self, request: product_search_service.CreateProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_product Override in a subclass to manipulate the request or metadata @@ -242,9 +233,7 @@ def pre_create_product( """ return request, metadata - def post_create_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_create_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for create_product DEPRECATED. Please use the `post_create_product_with_metadata` @@ -257,11 +246,7 @@ def post_create_product( """ return response - def post_create_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_product Override in a subclass to read or manipulate the response or metadata after it @@ -276,14 +261,7 @@ def post_create_product_with_metadata( """ return response, metadata - def pre_create_product_set( - self, - request: product_search_service.CreateProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_product_set(self, request: product_search_service.CreateProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_product_set Override in a subclass to manipulate the request or metadata @@ -291,9 +269,7 @@ def pre_create_product_set( """ return request, metadata - def post_create_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_create_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for create_product_set DEPRECATED. Please use the `post_create_product_set_with_metadata` @@ -306,13 +282,7 @@ def post_create_product_set( """ return response - def post_create_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_create_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -327,14 +297,7 @@ def post_create_product_set_with_metadata( """ return response, metadata - def pre_create_reference_image( - self, - request: product_search_service.CreateReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.CreateReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_create_reference_image(self, request: product_search_service.CreateReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.CreateReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_reference_image Override in a subclass to manipulate the request or metadata @@ -342,9 +305,7 @@ def pre_create_reference_image( """ return request, metadata - def post_create_reference_image( - self, response: product_search_service.ReferenceImage - ) -> product_search_service.ReferenceImage: + def post_create_reference_image(self, response: product_search_service.ReferenceImage) -> product_search_service.ReferenceImage: """Post-rpc interceptor for create_reference_image DEPRECATED. Please use the `post_create_reference_image_with_metadata` @@ -357,13 +318,7 @@ def post_create_reference_image( """ return response - def post_create_reference_image_with_metadata( - self, - response: product_search_service.ReferenceImage, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_create_reference_image_with_metadata(self, response: product_search_service.ReferenceImage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_reference_image Override in a subclass to read or manipulate the response or metadata after it @@ -378,14 +333,7 @@ def post_create_reference_image_with_metadata( """ return response, metadata - def pre_delete_product( - self, - request: product_search_service.DeleteProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_product(self, request: product_search_service.DeleteProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_product Override in a subclass to manipulate the request or metadata @@ -393,14 +341,7 @@ def pre_delete_product( """ return request, metadata - def pre_delete_product_set( - self, - request: product_search_service.DeleteProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_product_set(self, request: product_search_service.DeleteProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_product_set Override in a subclass to manipulate the request or metadata @@ -408,14 +349,7 @@ def pre_delete_product_set( """ return request, metadata - def pre_delete_reference_image( - self, - request: product_search_service.DeleteReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.DeleteReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_delete_reference_image(self, request: product_search_service.DeleteReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.DeleteReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_reference_image Override in a subclass to manipulate the request or metadata @@ -423,14 +357,7 @@ def pre_delete_reference_image( """ return request, metadata - def pre_get_product( - self, - request: product_search_service.GetProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_product(self, request: product_search_service.GetProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_product Override in a subclass to manipulate the request or metadata @@ -438,9 +365,7 @@ def pre_get_product( """ return request, metadata - def post_get_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_get_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for get_product DEPRECATED. Please use the `post_get_product_with_metadata` @@ -453,11 +378,7 @@ def post_get_product( """ return response - def post_get_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_product Override in a subclass to read or manipulate the response or metadata after it @@ -472,14 +393,7 @@ def post_get_product_with_metadata( """ return response, metadata - def pre_get_product_set( - self, - request: product_search_service.GetProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_product_set(self, request: product_search_service.GetProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_product_set Override in a subclass to manipulate the request or metadata @@ -487,9 +401,7 @@ def pre_get_product_set( """ return request, metadata - def post_get_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_get_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for get_product_set DEPRECATED. Please use the `post_get_product_set_with_metadata` @@ -502,13 +414,7 @@ def post_get_product_set( """ return response - def post_get_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_get_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -523,14 +429,7 @@ def post_get_product_set_with_metadata( """ return response, metadata - def pre_get_reference_image( - self, - request: product_search_service.GetReferenceImageRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.GetReferenceImageRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_get_reference_image(self, request: product_search_service.GetReferenceImageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.GetReferenceImageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_reference_image Override in a subclass to manipulate the request or metadata @@ -538,9 +437,7 @@ def pre_get_reference_image( """ return request, metadata - def post_get_reference_image( - self, response: product_search_service.ReferenceImage - ) -> product_search_service.ReferenceImage: + def post_get_reference_image(self, response: product_search_service.ReferenceImage) -> product_search_service.ReferenceImage: """Post-rpc interceptor for get_reference_image DEPRECATED. Please use the `post_get_reference_image_with_metadata` @@ -553,13 +450,7 @@ def post_get_reference_image( """ return response - def post_get_reference_image_with_metadata( - self, - response: product_search_service.ReferenceImage, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_get_reference_image_with_metadata(self, response: product_search_service.ReferenceImage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ReferenceImage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_reference_image Override in a subclass to read or manipulate the response or metadata after it @@ -574,14 +465,7 @@ def post_get_reference_image_with_metadata( """ return response, metadata - def pre_import_product_sets( - self, - request: product_search_service.ImportProductSetsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ImportProductSetsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_import_product_sets(self, request: product_search_service.ImportProductSetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ImportProductSetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for import_product_sets Override in a subclass to manipulate the request or metadata @@ -589,9 +473,7 @@ def pre_import_product_sets( """ return request, metadata - def post_import_product_sets( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_import_product_sets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for import_product_sets DEPRECATED. Please use the `post_import_product_sets_with_metadata` @@ -604,11 +486,7 @@ def post_import_product_sets( """ return response - def post_import_product_sets_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_import_product_sets_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for import_product_sets Override in a subclass to read or manipulate the response or metadata after it @@ -623,14 +501,7 @@ def post_import_product_sets_with_metadata( """ return response, metadata - def pre_list_products( - self, - request: product_search_service.ListProductsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_products(self, request: product_search_service.ListProductsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_products Override in a subclass to manipulate the request or metadata @@ -638,9 +509,7 @@ def pre_list_products( """ return request, metadata - def post_list_products( - self, response: product_search_service.ListProductsResponse - ) -> product_search_service.ListProductsResponse: + def post_list_products(self, response: product_search_service.ListProductsResponse) -> product_search_service.ListProductsResponse: """Post-rpc interceptor for list_products DEPRECATED. Please use the `post_list_products_with_metadata` @@ -653,14 +522,7 @@ def post_list_products( """ return response - def post_list_products_with_metadata( - self, - response: product_search_service.ListProductsResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_products_with_metadata(self, response: product_search_service.ListProductsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_products Override in a subclass to read or manipulate the response or metadata after it @@ -675,14 +537,7 @@ def post_list_products_with_metadata( """ return response, metadata - def pre_list_product_sets( - self, - request: product_search_service.ListProductSetsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductSetsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_product_sets(self, request: product_search_service.ListProductSetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductSetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_product_sets Override in a subclass to manipulate the request or metadata @@ -690,9 +545,7 @@ def pre_list_product_sets( """ return request, metadata - def post_list_product_sets( - self, response: product_search_service.ListProductSetsResponse - ) -> product_search_service.ListProductSetsResponse: + def post_list_product_sets(self, response: product_search_service.ListProductSetsResponse) -> product_search_service.ListProductSetsResponse: """Post-rpc interceptor for list_product_sets DEPRECATED. Please use the `post_list_product_sets_with_metadata` @@ -705,14 +558,7 @@ def post_list_product_sets( """ return response - def post_list_product_sets_with_metadata( - self, - response: product_search_service.ListProductSetsResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductSetsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_product_sets_with_metadata(self, response: product_search_service.ListProductSetsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductSetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_product_sets Override in a subclass to read or manipulate the response or metadata after it @@ -727,14 +573,7 @@ def post_list_product_sets_with_metadata( """ return response, metadata - def pre_list_products_in_product_set( - self, - request: product_search_service.ListProductsInProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsInProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_products_in_product_set(self, request: product_search_service.ListProductsInProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsInProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_products_in_product_set Override in a subclass to manipulate the request or metadata @@ -742,9 +581,7 @@ def pre_list_products_in_product_set( """ return request, metadata - def post_list_products_in_product_set( - self, response: product_search_service.ListProductsInProductSetResponse - ) -> product_search_service.ListProductsInProductSetResponse: + def post_list_products_in_product_set(self, response: product_search_service.ListProductsInProductSetResponse) -> product_search_service.ListProductsInProductSetResponse: """Post-rpc interceptor for list_products_in_product_set DEPRECATED. Please use the `post_list_products_in_product_set_with_metadata` @@ -757,14 +594,7 @@ def post_list_products_in_product_set( """ return response - def post_list_products_in_product_set_with_metadata( - self, - response: product_search_service.ListProductsInProductSetResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListProductsInProductSetResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_products_in_product_set_with_metadata(self, response: product_search_service.ListProductsInProductSetResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListProductsInProductSetResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_products_in_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -779,14 +609,7 @@ def post_list_products_in_product_set_with_metadata( """ return response, metadata - def pre_list_reference_images( - self, - request: product_search_service.ListReferenceImagesRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListReferenceImagesRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_list_reference_images(self, request: product_search_service.ListReferenceImagesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListReferenceImagesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_reference_images Override in a subclass to manipulate the request or metadata @@ -794,9 +617,7 @@ def pre_list_reference_images( """ return request, metadata - def post_list_reference_images( - self, response: product_search_service.ListReferenceImagesResponse - ) -> product_search_service.ListReferenceImagesResponse: + def post_list_reference_images(self, response: product_search_service.ListReferenceImagesResponse) -> product_search_service.ListReferenceImagesResponse: """Post-rpc interceptor for list_reference_images DEPRECATED. Please use the `post_list_reference_images_with_metadata` @@ -809,14 +630,7 @@ def post_list_reference_images( """ return response - def post_list_reference_images_with_metadata( - self, - response: product_search_service.ListReferenceImagesResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ListReferenceImagesResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def post_list_reference_images_with_metadata(self, response: product_search_service.ListReferenceImagesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ListReferenceImagesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_reference_images Override in a subclass to read or manipulate the response or metadata after it @@ -831,14 +645,7 @@ def post_list_reference_images_with_metadata( """ return response, metadata - def pre_purge_products( - self, - request: product_search_service.PurgeProductsRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.PurgeProductsRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_purge_products(self, request: product_search_service.PurgeProductsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.PurgeProductsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for purge_products Override in a subclass to manipulate the request or metadata @@ -846,9 +653,7 @@ def pre_purge_products( """ return request, metadata - def post_purge_products( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: + def post_purge_products(self, response: operations_pb2.Operation) -> operations_pb2.Operation: """Post-rpc interceptor for purge_products DEPRECATED. Please use the `post_purge_products_with_metadata` @@ -861,11 +666,7 @@ def post_purge_products( """ return response - def post_purge_products_with_metadata( - self, - response: operations_pb2.Operation, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_purge_products_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for purge_products Override in a subclass to read or manipulate the response or metadata after it @@ -880,14 +681,7 @@ def post_purge_products_with_metadata( """ return response, metadata - def pre_remove_product_from_product_set( - self, - request: product_search_service.RemoveProductFromProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.RemoveProductFromProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_remove_product_from_product_set(self, request: product_search_service.RemoveProductFromProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.RemoveProductFromProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for remove_product_from_product_set Override in a subclass to manipulate the request or metadata @@ -895,14 +689,7 @@ def pre_remove_product_from_product_set( """ return request, metadata - def pre_update_product( - self, - request: product_search_service.UpdateProductRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.UpdateProductRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_update_product(self, request: product_search_service.UpdateProductRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.UpdateProductRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_product Override in a subclass to manipulate the request or metadata @@ -910,9 +697,7 @@ def pre_update_product( """ return request, metadata - def post_update_product( - self, response: product_search_service.Product - ) -> product_search_service.Product: + def post_update_product(self, response: product_search_service.Product) -> product_search_service.Product: """Post-rpc interceptor for update_product DEPRECATED. Please use the `post_update_product_with_metadata` @@ -925,11 +710,7 @@ def post_update_product( """ return response - def post_update_product_with_metadata( - self, - response: product_search_service.Product, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_product_with_metadata(self, response: product_search_service.Product, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.Product, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_product Override in a subclass to read or manipulate the response or metadata after it @@ -944,14 +725,7 @@ def post_update_product_with_metadata( """ return response, metadata - def pre_update_product_set( - self, - request: product_search_service.UpdateProductSetRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.UpdateProductSetRequest, - Sequence[Tuple[str, Union[str, bytes]]], - ]: + def pre_update_product_set(self, request: product_search_service.UpdateProductSetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.UpdateProductSetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_product_set Override in a subclass to manipulate the request or metadata @@ -959,9 +733,7 @@ def pre_update_product_set( """ return request, metadata - def post_update_product_set( - self, response: product_search_service.ProductSet - ) -> product_search_service.ProductSet: + def post_update_product_set(self, response: product_search_service.ProductSet) -> product_search_service.ProductSet: """Post-rpc interceptor for update_product_set DEPRECATED. Please use the `post_update_product_set_with_metadata` @@ -974,13 +746,7 @@ def post_update_product_set( """ return response - def post_update_product_set_with_metadata( - self, - response: product_search_service.ProductSet, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_update_product_set_with_metadata(self, response: product_search_service.ProductSet, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[product_search_service.ProductSet, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_product_set Override in a subclass to read or manipulate the response or metadata after it @@ -1009,22 +775,23 @@ class ProductSearchRestTransport(_BaseProductSearchRestTransport): Manages Products and ProductSets of reference images for use in product search. It uses the following resource model: - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, - named ``projects/*/locations/*/productSets/*``, which acts as a - way to put different products into groups to limit identification. + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. In parallel, - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - ``projects/*/locations/*/products/*`` + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a - collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] - resources, named - ``projects/*/locations/*/products/*/referenceImages/*`` + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -1033,21 +800,20 @@ class ProductSearchRestTransport(_BaseProductSearchRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[ProductSearchRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ProductSearchRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -1091,11 +857,10 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + 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) @@ -1111,28 +876,23 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: """ # 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]]] = {} + http_options: Dict[str, List[Dict[str, str]]] = { + } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1p4beta1", - ) - - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1p4beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) # Return the client from cache. return self._operations_client - class _AddProductToProductSet( - _BaseProductSearchRestTransport._BaseAddProductToProductSet, - ProductSearchRestStub, - ): + class _AddProductToProductSet(_BaseProductSearchRestTransport._BaseAddProductToProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.AddProductToProductSet") @@ -1144,85 +904,69 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.AddProductToProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.AddProductToProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the add product to product - set method over HTTP. - - Args: - request (~.product_search_service.AddProductToProductSetRequest): - The request object. Request message for the ``AddProductToProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + set method over HTTP. + + Args: + request (~.product_search_service.AddProductToProductSetRequest): + The request object. Request message for the ``AddProductToProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_http_options() - request, metadata = self._interceptor.pre_add_product_to_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_add_product_to_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.AddProductToProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "AddProductToProductSet", "httpRequest": http_request, @@ -1231,24 +975,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._AddProductToProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._AddProductToProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _CreateProduct( - _BaseProductSearchRestTransport._BaseCreateProduct, ProductSearchRestStub - ): + class _CreateProduct(_BaseProductSearchRestTransport._BaseCreateProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateProduct") @@ -1260,29 +994,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.CreateProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the create product method over HTTP. Args: @@ -1301,44 +1033,32 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateProduct._get_http_options() request, metadata = self._interceptor.pre_create_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateProduct._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateProduct._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateProduct._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.CreateProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "CreateProduct", "httpRequest": http_request, @@ -1347,15 +1067,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1370,24 +1082,20 @@ def __call__( resp = self._interceptor.post_create_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.create_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "CreateProduct", "metadata": http_response["headers"], @@ -1396,9 +1104,7 @@ def __call__( ) return resp - class _CreateProductSet( - _BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub - ): + class _CreateProductSet(_BaseProductSearchRestTransport._BaseCreateProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateProductSet") @@ -1410,29 +1116,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.CreateProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the create product set method over HTTP. Args: @@ -1456,46 +1160,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateProductSet._get_http_options() - request, metadata = self._interceptor.pre_create_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.CreateProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "CreateProductSet", "httpRequest": http_request, @@ -1504,15 +1194,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1527,26 +1209,20 @@ def __call__( resp = self._interceptor.post_create_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.create_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "CreateProductSet", "metadata": http_response["headers"], @@ -1555,9 +1231,7 @@ def __call__( ) return resp - class _CreateReferenceImage( - _BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub - ): + class _CreateReferenceImage(_BaseProductSearchRestTransport._BaseCreateReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.CreateReferenceImage") @@ -1569,29 +1243,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.CreateReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def __call__(self, + request: product_search_service.CreateReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ReferenceImage: r"""Call the create reference image method over HTTP. Args: @@ -1612,46 +1284,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_create_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_create_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.CreateReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "CreateReferenceImage", "httpRequest": http_request, @@ -1660,15 +1318,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._CreateReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._CreateReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1683,26 +1333,20 @@ def __call__( resp = self._interceptor.post_create_reference_image(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_reference_image_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_create_reference_image_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ReferenceImage.to_json( - response - ) + response_payload = product_search_service.ReferenceImage.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.create_reference_image", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "CreateReferenceImage", "metadata": http_response["headers"], @@ -1711,9 +1355,7 @@ def __call__( ) return resp - class _DeleteProduct( - _BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub - ): + class _DeleteProduct(_BaseProductSearchRestTransport._BaseDeleteProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProduct") @@ -1725,28 +1367,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete product method over HTTP. Args: @@ -1761,40 +1401,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteProduct._get_http_options() request, metadata = self._interceptor.pre_delete_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProduct._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.DeleteProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "DeleteProduct", "httpRequest": http_request, @@ -1803,23 +1433,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteProductSet( - _BaseProductSearchRestTransport._BaseDeleteProductSet, ProductSearchRestStub - ): + class _DeleteProductSet(_BaseProductSearchRestTransport._BaseDeleteProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteProductSet") @@ -1831,28 +1452,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete product set method over HTTP. Args: @@ -1867,42 +1486,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_http_options() - request, metadata = self._interceptor.pre_delete_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_delete_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.DeleteProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "DeleteProductSet", "httpRequest": http_request, @@ -1911,23 +1518,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteReferenceImage( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage, ProductSearchRestStub - ): + class _DeleteReferenceImage(_BaseProductSearchRestTransport._BaseDeleteReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.DeleteReferenceImage") @@ -1939,28 +1537,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.DeleteReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.DeleteReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the delete reference image method over HTTP. Args: @@ -1975,42 +1571,30 @@ def __call__( be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_delete_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_delete_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.DeleteReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "DeleteReferenceImage", "httpRequest": http_request, @@ -2019,23 +1603,14 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._DeleteReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._DeleteReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetProduct( - _BaseProductSearchRestTransport._BaseGetProduct, ProductSearchRestStub - ): + class _GetProduct(_BaseProductSearchRestTransport._BaseGetProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetProduct") @@ -2047,28 +1622,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.GetProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the get product method over HTTP. Args: @@ -2087,44 +1660,30 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetProduct._get_http_options() request, metadata = self._interceptor.pre_get_product(request, metadata) - transcoded_request = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_transcoded_request( - http_options, request - ) - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetProduct._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = ( - _BaseProductSearchRestTransport._BaseGetProduct._get_query_params_json( - transcoded_request - ) - ) + query_params = _BaseProductSearchRestTransport._BaseGetProduct._get_query_params_json(transcoded_request) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.GetProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "GetProduct", "httpRequest": http_request, @@ -2133,14 +1692,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2155,24 +1707,20 @@ def __call__( resp = self._interceptor.post_get_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.get_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "GetProduct", "metadata": http_response["headers"], @@ -2181,9 +1729,7 @@ def __call__( ) return resp - class _GetProductSet( - _BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub - ): + class _GetProductSet(_BaseProductSearchRestTransport._BaseGetProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetProductSet") @@ -2195,28 +1741,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.GetProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the get product set method over HTTP. Args: @@ -2240,40 +1784,30 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetProductSet._get_http_options() request, metadata = self._interceptor.pre_get_product_set(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseGetProductSet._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseGetProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.GetProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "GetProductSet", "httpRequest": http_request, @@ -2282,14 +1816,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2304,26 +1831,20 @@ def __call__( resp = self._interceptor.post_get_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.get_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "GetProductSet", "metadata": http_response["headers"], @@ -2332,9 +1853,7 @@ def __call__( ) return resp - class _GetReferenceImage( - _BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub - ): + class _GetReferenceImage(_BaseProductSearchRestTransport._BaseGetReferenceImage, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.GetReferenceImage") @@ -2346,28 +1865,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.GetReferenceImageRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ReferenceImage: + def __call__(self, + request: product_search_service.GetReferenceImageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ReferenceImage: r"""Call the get reference image method over HTTP. Args: @@ -2388,42 +1905,30 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseGetReferenceImage._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_http_options() - request, metadata = self._interceptor.pre_get_reference_image( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_get_reference_image(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseGetReferenceImage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.GetReferenceImage", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "GetReferenceImage", "httpRequest": http_request, @@ -2432,14 +1937,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._GetReferenceImage._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._GetReferenceImage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2454,26 +1952,20 @@ def __call__( resp = self._interceptor.post_get_reference_image(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_reference_image_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_get_reference_image_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ReferenceImage.to_json( - response - ) + response_payload = product_search_service.ReferenceImage.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.get_reference_image", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "GetReferenceImage", "metadata": http_response["headers"], @@ -2482,9 +1974,7 @@ def __call__( ) return resp - class _ImportProductSets( - _BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub - ): + class _ImportProductSets(_BaseProductSearchRestTransport._BaseImportProductSets, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ImportProductSets") @@ -2496,29 +1986,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.ImportProductSetsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: product_search_service.ImportProductSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the import product sets method over HTTP. Args: @@ -2540,46 +2028,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseImportProductSets._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseImportProductSets._get_http_options() - request, metadata = self._interceptor.pre_import_product_sets( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseImportProductSets._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_import_product_sets(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseImportProductSets._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseImportProductSets._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseImportProductSets._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseImportProductSets._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseImportProductSets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.ImportProductSets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ImportProductSets", "httpRequest": http_request, @@ -2588,15 +2062,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ImportProductSets._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._ImportProductSets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2609,24 +2075,20 @@ def __call__( resp = self._interceptor.post_import_product_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_import_product_sets_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_import_product_sets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.import_product_sets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ImportProductSets", "metadata": http_response["headers"], @@ -2635,9 +2097,7 @@ def __call__( ) return resp - class _ListProducts( - _BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub - ): + class _ListProducts(_BaseProductSearchRestTransport._BaseListProducts, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProducts") @@ -2649,28 +2109,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductsResponse: + def __call__(self, + request: product_search_service.ListProductsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductsResponse: r"""Call the list products method over HTTP. Args: @@ -2689,40 +2147,30 @@ def __call__( Response message for the ``ListProducts`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProducts._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProducts._get_http_options() request, metadata = self._interceptor.pre_list_products(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseListProducts._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseListProducts._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProducts._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProducts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.ListProducts", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListProducts", "httpRequest": http_request, @@ -2731,14 +2179,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListProducts._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2753,26 +2194,20 @@ def __call__( resp = self._interceptor.post_list_products(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_products_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_products_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductsResponse.to_json(response) - ) + response_payload = product_search_service.ListProductsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.list_products", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListProducts", "metadata": http_response["headers"], @@ -2781,9 +2216,7 @@ def __call__( ) return resp - class _ListProductSets( - _BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub - ): + class _ListProductSets(_BaseProductSearchRestTransport._BaseListProductSets, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProductSets") @@ -2795,28 +2228,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductSetsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductSetsResponse: + def __call__(self, + request: product_search_service.ListProductSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductSetsResponse: r"""Call the list product sets method over HTTP. Args: @@ -2835,42 +2266,30 @@ def __call__( Response message for the ``ListProductSets`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProductSets._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProductSets._get_http_options() - request, metadata = self._interceptor.pre_list_product_sets( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListProductSets._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_product_sets(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListProductSets._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProductSets._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProductSets._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.ListProductSets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListProductSets", "httpRequest": http_request, @@ -2879,14 +2298,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListProductSets._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListProductSets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2901,26 +2313,20 @@ def __call__( resp = self._interceptor.post_list_product_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_product_sets_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_product_sets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductSetsResponse.to_json(response) - ) + response_payload = product_search_service.ListProductSetsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.list_product_sets", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListProductSets", "metadata": http_response["headers"], @@ -2929,10 +2335,7 @@ def __call__( ) return resp - class _ListProductsInProductSet( - _BaseProductSearchRestTransport._BaseListProductsInProductSet, - ProductSearchRestStub, - ): + class _ListProductsInProductSet(_BaseProductSearchRestTransport._BaseListProductsInProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListProductsInProductSet") @@ -2944,86 +2347,72 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListProductsInProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListProductsInProductSetResponse: + def __call__(self, + request: product_search_service.ListProductsInProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListProductsInProductSetResponse: r"""Call the list products in product - set method over HTTP. - - Args: - request (~.product_search_service.ListProductsInProductSetRequest): - The request object. Request message for the ``ListProductsInProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.product_search_service.ListProductsInProductSetResponse: - Response message for the ``ListProductsInProductSet`` - method. + set method over HTTP. + + Args: + request (~.product_search_service.ListProductsInProductSetRequest): + The request object. Request message for the ``ListProductsInProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.product_search_service.ListProductsInProductSetResponse: + Response message for the ``ListProductsInProductSet`` + method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_http_options() - request, metadata = self._interceptor.pre_list_products_in_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_products_in_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.ListProductsInProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListProductsInProductSet", "httpRequest": http_request, @@ -3032,16 +2421,7 @@ def __call__( ) # Send the request - response = ( - ProductSearchRestTransport._ListProductsInProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) - ) + response = ProductSearchRestTransport._ListProductsInProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3056,28 +2436,20 @@ def __call__( resp = self._interceptor.post_list_products_in_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_products_in_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_products_in_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListProductsInProductSetResponse.to_json( - response - ) - ) + response_payload = product_search_service.ListProductsInProductSetResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.list_products_in_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListProductsInProductSet", "metadata": http_response["headers"], @@ -3086,9 +2458,7 @@ def __call__( ) return resp - class _ListReferenceImages( - _BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub - ): + class _ListReferenceImages(_BaseProductSearchRestTransport._BaseListReferenceImages, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.ListReferenceImages") @@ -3100,28 +2470,26 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__( - self, - request: product_search_service.ListReferenceImagesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ListReferenceImagesResponse: + def __call__(self, + request: product_search_service.ListReferenceImagesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ListReferenceImagesResponse: r"""Call the list reference images method over HTTP. Args: @@ -3140,42 +2508,30 @@ def __call__( Response message for the ``ListReferenceImages`` method. """ - http_options = ( - _BaseProductSearchRestTransport._BaseListReferenceImages._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseListReferenceImages._get_http_options() - request, metadata = self._interceptor.pre_list_reference_images( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseListReferenceImages._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_reference_images(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseListReferenceImages._get_transcoded_request(http_options, request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseListReferenceImages._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseListReferenceImages._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.ListReferenceImages", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListReferenceImages", "httpRequest": http_request, @@ -3184,14 +2540,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._ListReferenceImages._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = ProductSearchRestTransport._ListReferenceImages._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3206,28 +2555,20 @@ def __call__( resp = self._interceptor.post_list_reference_images(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_reference_images_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_list_reference_images_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = ( - product_search_service.ListReferenceImagesResponse.to_json( - response - ) - ) + response_payload = product_search_service.ListReferenceImagesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.list_reference_images", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "ListReferenceImages", "metadata": http_response["headers"], @@ -3236,9 +2577,7 @@ def __call__( ) return resp - class _PurgeProducts( - _BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub - ): + class _PurgeProducts(_BaseProductSearchRestTransport._BasePurgeProducts, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.PurgeProducts") @@ -3250,29 +2589,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.PurgeProductsRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: + def __call__(self, + request: product_search_service.PurgeProductsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: r"""Call the purge products method over HTTP. Args: @@ -3294,44 +2631,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BasePurgeProducts._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BasePurgeProducts._get_http_options() request, metadata = self._interceptor.pre_purge_products(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BasePurgeProducts._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BasePurgeProducts._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BasePurgeProducts._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BasePurgeProducts._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BasePurgeProducts._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BasePurgeProducts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.PurgeProducts", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "PurgeProducts", "httpRequest": http_request, @@ -3340,15 +2665,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._PurgeProducts._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._PurgeProducts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3361,24 +2678,20 @@ def __call__( resp = self._interceptor.post_purge_products(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_purge_products_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_purge_products_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.purge_products", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "PurgeProducts", "metadata": http_response["headers"], @@ -3387,10 +2700,7 @@ def __call__( ) return resp - class _RemoveProductFromProductSet( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, - ProductSearchRestStub, - ): + class _RemoveProductFromProductSet(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.RemoveProductFromProductSet") @@ -3402,85 +2712,69 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.RemoveProductFromProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): + def __call__(self, + request: product_search_service.RemoveProductFromProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): r"""Call the remove product from - product set method over HTTP. - - Args: - request (~.product_search_service.RemoveProductFromProductSetRequest): - The request object. Request message for the ``RemoveProductFromProductSet`` - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + product set method over HTTP. + + Args: + request (~.product_search_service.RemoveProductFromProductSetRequest): + The request object. Request message for the ``RemoveProductFromProductSet`` + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ - http_options = ( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_http_options() - request, metadata = self._interceptor.pre_remove_product_from_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_remove_product_from_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.RemoveProductFromProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "RemoveProductFromProductSet", "httpRequest": http_request, @@ -3489,26 +2783,14 @@ def __call__( ) # Send the request - response = ( - ProductSearchRestTransport._RemoveProductFromProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) - ) + response = ProductSearchRestTransport._RemoveProductFromProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _UpdateProduct( - _BaseProductSearchRestTransport._BaseUpdateProduct, ProductSearchRestStub - ): + class _UpdateProduct(_BaseProductSearchRestTransport._BaseUpdateProduct, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProduct") @@ -3520,29 +2802,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.UpdateProductRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.Product: + def __call__(self, + request: product_search_service.UpdateProductRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.Product: r"""Call the update product method over HTTP. Args: @@ -3561,44 +2841,32 @@ def __call__( A Product contains ReferenceImages. """ - http_options = ( - _BaseProductSearchRestTransport._BaseUpdateProduct._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseUpdateProduct._get_http_options() request, metadata = self._interceptor.pre_update_product(request, metadata) - transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProduct._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProduct._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseUpdateProduct._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseUpdateProduct._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseUpdateProduct._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseUpdateProduct._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.UpdateProduct", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "UpdateProduct", "httpRequest": http_request, @@ -3607,15 +2875,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._UpdateProduct._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._UpdateProduct._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3630,24 +2890,20 @@ def __call__( resp = self._interceptor.post_update_product(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_product_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_update_product_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = product_search_service.Product.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.update_product", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "UpdateProduct", "metadata": http_response["headers"], @@ -3656,9 +2912,7 @@ def __call__( ) return resp - class _UpdateProductSet( - _BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub - ): + class _UpdateProductSet(_BaseProductSearchRestTransport._BaseUpdateProductSet, ProductSearchRestStub): def __hash__(self): return hash("ProductSearchRestTransport.UpdateProductSet") @@ -3670,29 +2924,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: product_search_service.UpdateProductSetRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> product_search_service.ProductSet: + def __call__(self, + request: product_search_service.UpdateProductSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> product_search_service.ProductSet: r"""Call the update product set method over HTTP. Args: @@ -3716,46 +2968,32 @@ def __call__( """ - http_options = ( - _BaseProductSearchRestTransport._BaseUpdateProductSet._get_http_options() - ) + http_options = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_http_options() - request, metadata = self._interceptor.pre_update_product_set( - request, metadata - ) - transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_product_set(request, metadata) + transcoded_request = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_transcoded_request(http_options, request) - body = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_request_body_json( - transcoded_request - ) + body = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseProductSearchRestTransport._BaseUpdateProductSet._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.vision_v1p4beta1.ProductSearchClient.UpdateProductSet", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "UpdateProductSet", "httpRequest": http_request, @@ -3764,15 +3002,7 @@ def __call__( ) # Send the request - response = ProductSearchRestTransport._UpdateProductSet._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = ProductSearchRestTransport._UpdateProductSet._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3787,26 +3017,20 @@ def __call__( resp = self._interceptor.post_update_product_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_product_set_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_update_product_set_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = product_search_service.ProductSet.to_json( - response - ) + response_payload = product_search_service.ProductSet.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.vision_v1p4beta1.ProductSearchClient.update_product_set", - extra={ + extra = { "serviceName": "google.cloud.vision.v1p4beta1.ProductSearch", "rpcName": "UpdateProductSet", "metadata": http_response["headers"], @@ -3816,198 +3040,156 @@ def __call__( return resp @property - def add_product_to_product_set( - self, - ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], empty_pb2.Empty - ]: + def add_product_to_product_set(self) -> Callable[ + [product_search_service.AddProductToProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AddProductToProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._AddProductToProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def create_product( - self, - ) -> Callable[ - [product_search_service.CreateProductRequest], product_search_service.Product - ]: + def create_product(self) -> Callable[ + [product_search_service.CreateProductRequest], + product_search_service.Product]: # 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._CreateProduct(self._session, self._host, self._interceptor) # type: ignore + return self._CreateProduct(self._session, self._host, self._interceptor) # type: ignore @property - def create_product_set( - self, - ) -> Callable[ - [product_search_service.CreateProductSetRequest], - product_search_service.ProductSet, - ]: + def create_product_set(self) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet]: # 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._CreateProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._CreateProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def create_reference_image( - self, - ) -> Callable[ - [product_search_service.CreateReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def create_reference_image(self) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage]: # 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._CreateReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._CreateReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def delete_product( - self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: + def delete_product(self) -> Callable[ + [product_search_service.DeleteProductRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteProduct(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteProduct(self._session, self._host, self._interceptor) # type: ignore @property - def delete_product_set( - self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: + def delete_product_set(self) -> Callable[ + [product_search_service.DeleteProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def delete_reference_image( - self, - ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty - ]: + def delete_reference_image(self) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def get_product( - self, - ) -> Callable[ - [product_search_service.GetProductRequest], product_search_service.Product - ]: + def get_product(self) -> Callable[ + [product_search_service.GetProductRequest], + product_search_service.Product]: # 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._GetProduct(self._session, self._host, self._interceptor) # type: ignore + return self._GetProduct(self._session, self._host, self._interceptor) # type: ignore @property - def get_product_set( - self, - ) -> Callable[ - [product_search_service.GetProductSetRequest], product_search_service.ProductSet - ]: + def get_product_set(self) -> Callable[ + [product_search_service.GetProductSetRequest], + product_search_service.ProductSet]: # 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._GetProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._GetProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def get_reference_image( - self, - ) -> Callable[ - [product_search_service.GetReferenceImageRequest], - product_search_service.ReferenceImage, - ]: + def get_reference_image(self) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage]: # 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._GetReferenceImage(self._session, self._host, self._interceptor) # type: ignore + return self._GetReferenceImage(self._session, self._host, self._interceptor) # type: ignore @property - def import_product_sets( - self, - ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations_pb2.Operation - ]: + def import_product_sets(self) -> Callable[ + [product_search_service.ImportProductSetsRequest], + 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._ImportProductSets(self._session, self._host, self._interceptor) # type: ignore + return self._ImportProductSets(self._session, self._host, self._interceptor) # type: ignore @property - def list_products( - self, - ) -> Callable[ - [product_search_service.ListProductsRequest], - product_search_service.ListProductsResponse, - ]: + def list_products(self) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse]: # 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._ListProducts(self._session, self._host, self._interceptor) # type: ignore + return self._ListProducts(self._session, self._host, self._interceptor) # type: ignore @property - def list_product_sets( - self, - ) -> Callable[ - [product_search_service.ListProductSetsRequest], - product_search_service.ListProductSetsResponse, - ]: + def list_product_sets(self) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse]: # 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._ListProductSets(self._session, self._host, self._interceptor) # type: ignore + return self._ListProductSets(self._session, self._host, self._interceptor) # type: ignore @property - def list_products_in_product_set( - self, - ) -> Callable[ - [product_search_service.ListProductsInProductSetRequest], - product_search_service.ListProductsInProductSetResponse, - ]: + def list_products_in_product_set(self) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse]: # 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._ListProductsInProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._ListProductsInProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def list_reference_images( - self, - ) -> Callable[ - [product_search_service.ListReferenceImagesRequest], - product_search_service.ListReferenceImagesResponse, - ]: + def list_reference_images(self) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse]: # 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._ListReferenceImages(self._session, self._host, self._interceptor) # type: ignore + return self._ListReferenceImages(self._session, self._host, self._interceptor) # type: ignore @property - def purge_products( - self, - ) -> Callable[ - [product_search_service.PurgeProductsRequest], operations_pb2.Operation - ]: + def purge_products(self) -> Callable[ + [product_search_service.PurgeProductsRequest], + 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._PurgeProducts(self._session, self._host, self._interceptor) # type: ignore + return self._PurgeProducts(self._session, self._host, self._interceptor) # type: ignore @property - def remove_product_from_product_set( - self, - ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty - ]: + def remove_product_from_product_set(self) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._RemoveProductFromProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._RemoveProductFromProductSet(self._session, self._host, self._interceptor) # type: ignore @property - def update_product( - self, - ) -> Callable[ - [product_search_service.UpdateProductRequest], product_search_service.Product - ]: + def update_product(self) -> Callable[ + [product_search_service.UpdateProductRequest], + product_search_service.Product]: # 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._UpdateProduct(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateProduct(self._session, self._host, self._interceptor) # type: ignore @property - def update_product_set( - self, - ) -> Callable[ - [product_search_service.UpdateProductSetRequest], - product_search_service.ProductSet, - ]: + def update_product_set(self) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet]: # 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._UpdateProductSet(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateProductSet(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -4017,4 +3199,6 @@ def close(self): self._session.close() -__all__ = ("ProductSearchRestTransport",) +__all__=( + 'ProductSearchRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest_base.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest_base.py index 81775562e533..9b869a65a40d 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest_base.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/services/product_search/transports/rest_base.py @@ -14,17 +14,19 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import json_format from google.cloud.vision_v1p4beta1.types import product_search_service - -from .base import DEFAULT_CLIENT_INFO, ProductSearchTransport +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore class _BaseProductSearchRestTransport(ProductSearchTransport): @@ -40,16 +42,14 @@ class _BaseProductSearchRestTransport(ProductSearchTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "vision.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'vision.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -73,9 +73,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -86,39 +84,33 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseAddProductToProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct', + 'body': '*', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.AddProductToProductSetRequest.pb( - request - ) + pb_request = product_search_service.AddProductToProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -127,23 +119,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseAddProductToProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseAddProductToProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -152,24 +138,20 @@ class _BaseCreateProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{parent=projects/*/locations/*}/products", - "body": "product", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*}/products', + 'body': 'product', + }, ] return http_options @@ -184,23 +166,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -209,24 +185,20 @@ class _BaseCreateProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{parent=projects/*/locations/*}/productSets", - "body": "product_set", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*}/productSets', + 'body': 'product_set', + }, ] return http_options @@ -241,23 +213,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -266,24 +232,20 @@ class _BaseCreateReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages", - "body": "reference_image", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages', + 'body': 'reference_image', + }, ] return http_options @@ -298,23 +260,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseCreateReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseCreateReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -323,23 +279,19 @@ class _BaseDeleteProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1p4beta1/{name=projects/*/locations/*/products/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/products/*}', + }, ] return http_options @@ -351,17 +303,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -370,23 +316,19 @@ class _BaseDeleteProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1p4beta1/{name=projects/*/locations/*/productSets/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/productSets/*}', + }, ] return http_options @@ -398,17 +340,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -417,23 +353,19 @@ class _BaseDeleteReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}', + }, ] return http_options @@ -445,17 +377,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseDeleteReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -464,23 +390,19 @@ class _BaseGetProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{name=projects/*/locations/*/products/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/products/*}', + }, ] return http_options @@ -492,17 +414,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -511,23 +427,19 @@ class _BaseGetProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{name=projects/*/locations/*/productSets/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/productSets/*}', + }, ] return http_options @@ -539,17 +451,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -558,23 +464,19 @@ class _BaseGetReferenceImage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}', + }, ] return http_options @@ -586,17 +488,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseGetReferenceImage._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseGetReferenceImage._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -605,24 +501,20 @@ class _BaseImportProductSets: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{parent=projects/*/locations/*}/productSets:import", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*}/productSets:import', + 'body': '*', + }, ] return http_options @@ -637,23 +529,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseImportProductSets._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseImportProductSets._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -662,23 +548,19 @@ class _BaseListProducts: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{parent=projects/*/locations/*}/products", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*}/products', + }, ] return http_options @@ -690,17 +572,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProducts._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProducts._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -709,23 +585,19 @@ class _BaseListProductSets: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{parent=projects/*/locations/*}/productSets", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*}/productSets', + }, ] return http_options @@ -737,17 +609,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProductSets._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProductSets._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -756,47 +622,35 @@ class _BaseListProductsInProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.ListProductsInProductSetRequest.pb( - request - ) + pb_request = product_search_service.ListProductsInProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListProductsInProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListProductsInProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -805,23 +659,19 @@ class _BaseListReferenceImages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages', + }, ] return http_options @@ -833,17 +683,11 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseListReferenceImages._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseListReferenceImages._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -852,24 +696,20 @@ class _BasePurgeProducts: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{parent=projects/*/locations/*}/products:purge", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{parent=projects/*/locations/*}/products:purge', + 'body': '*', + }, ] return http_options @@ -884,23 +724,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BasePurgeProducts._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BasePurgeProducts._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -909,32 +743,26 @@ class _BaseRemoveProductFromProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct', + 'body': '*', + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = product_search_service.RemoveProductFromProductSetRequest.pb( - request - ) + pb_request = product_search_service.RemoveProductFromProductSetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -943,23 +771,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseRemoveProductFromProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -968,24 +790,20 @@ class _BaseUpdateProduct: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1p4beta1/{product.name=projects/*/locations/*/products/*}", - "body": "product", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p4beta1/{product.name=projects/*/locations/*/products/*}', + 'body': 'product', + }, ] return http_options @@ -1000,23 +818,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseUpdateProduct._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseUpdateProduct._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -1025,24 +837,20 @@ class _BaseUpdateProductSet: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}", - "body": "product_set", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}', + 'body': 'product_set', + }, ] return http_options @@ -1057,26 +865,22 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + transcoded_request['body'], + use_integers_for_enums=True ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update( - _BaseProductSearchRestTransport._BaseUpdateProductSet._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseProductSearchRestTransport._BaseUpdateProductSet._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__ = ("_BaseProductSearchRestTransport",) +__all__=( + '_BaseProductSearchRestTransport', +) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/__init__.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/__init__.py index fd13455ce39b..a57865defa58 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/__init__.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/__init__.py @@ -13,8 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .face import Celebrity, FaceRecognitionParams, FaceRecognitionResult -from .geometry import BoundingPoly, NormalizedVertex, Position, Vertex +from .face import ( + Celebrity, + FaceRecognitionParams, + FaceRecognitionResult, +) +from .geometry import ( + BoundingPoly, + NormalizedVertex, + Position, + Vertex, +) from .image_annotator import ( AnnotateFileRequest, AnnotateFileResponse, @@ -47,7 +56,6 @@ ImageSource, InputConfig, LatLongRect, - Likelihood, LocalizedObjectAnnotation, LocationInfo, OperationMetadata, @@ -56,8 +64,12 @@ SafeSearchAnnotation, TextDetectionParams, WebDetectionParams, + Likelihood, +) +from .product_search import ( + ProductSearchParams, + ProductSearchResults, ) -from .product_search import ProductSearchParams, ProductSearchResults from .product_search_service import ( AddProductToProductSetRequest, BatchOperationMetadata, @@ -91,95 +103,104 @@ UpdateProductRequest, UpdateProductSetRequest, ) -from .text_annotation import Block, Page, Paragraph, Symbol, TextAnnotation, Word -from .web_detection import WebDetection +from .text_annotation import ( + Block, + Page, + Paragraph, + Symbol, + TextAnnotation, + Word, +) +from .web_detection import ( + WebDetection, +) __all__ = ( - "Celebrity", - "FaceRecognitionParams", - "FaceRecognitionResult", - "BoundingPoly", - "NormalizedVertex", - "Position", - "Vertex", - "AnnotateFileRequest", - "AnnotateFileResponse", - "AnnotateImageRequest", - "AnnotateImageResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "ColorInfo", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "DominantColorsAnnotation", - "EntityAnnotation", - "FaceAnnotation", - "Feature", - "GcsDestination", - "GcsSource", - "Image", - "ImageAnnotationContext", - "ImageContext", - "ImageProperties", - "ImageSource", - "InputConfig", - "LatLongRect", - "LocalizedObjectAnnotation", - "LocationInfo", - "OperationMetadata", - "OutputConfig", - "Property", - "SafeSearchAnnotation", - "TextDetectionParams", - "WebDetectionParams", - "Likelihood", - "ProductSearchParams", - "ProductSearchResults", - "AddProductToProductSetRequest", - "BatchOperationMetadata", - "CreateProductRequest", - "CreateProductSetRequest", - "CreateReferenceImageRequest", - "DeleteProductRequest", - "DeleteProductSetRequest", - "DeleteReferenceImageRequest", - "GetProductRequest", - "GetProductSetRequest", - "GetReferenceImageRequest", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "ListProductSetsRequest", - "ListProductSetsResponse", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ListProductsRequest", - "ListProductsResponse", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "Product", - "ProductSet", - "ProductSetPurgeConfig", - "PurgeProductsRequest", - "ReferenceImage", - "RemoveProductFromProductSetRequest", - "UpdateProductRequest", - "UpdateProductSetRequest", - "Block", - "Page", - "Paragraph", - "Symbol", - "TextAnnotation", - "Word", - "WebDetection", + 'Celebrity', + 'FaceRecognitionParams', + 'FaceRecognitionResult', + 'BoundingPoly', + 'NormalizedVertex', + 'Position', + 'Vertex', + 'AnnotateFileRequest', + 'AnnotateFileResponse', + 'AnnotateImageRequest', + 'AnnotateImageResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'AsyncBatchAnnotateImagesRequest', + 'AsyncBatchAnnotateImagesResponse', + 'BatchAnnotateFilesRequest', + 'BatchAnnotateFilesResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'ColorInfo', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'DominantColorsAnnotation', + 'EntityAnnotation', + 'FaceAnnotation', + 'Feature', + 'GcsDestination', + 'GcsSource', + 'Image', + 'ImageAnnotationContext', + 'ImageContext', + 'ImageProperties', + 'ImageSource', + 'InputConfig', + 'LatLongRect', + 'LocalizedObjectAnnotation', + 'LocationInfo', + 'OperationMetadata', + 'OutputConfig', + 'Property', + 'SafeSearchAnnotation', + 'TextDetectionParams', + 'WebDetectionParams', + 'Likelihood', + 'ProductSearchParams', + 'ProductSearchResults', + 'AddProductToProductSetRequest', + 'BatchOperationMetadata', + 'CreateProductRequest', + 'CreateProductSetRequest', + 'CreateReferenceImageRequest', + 'DeleteProductRequest', + 'DeleteProductSetRequest', + 'DeleteReferenceImageRequest', + 'GetProductRequest', + 'GetProductSetRequest', + 'GetReferenceImageRequest', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ListProductsRequest', + 'ListProductsResponse', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'Product', + 'ProductSet', + 'ProductSetPurgeConfig', + 'PurgeProductsRequest', + 'ReferenceImage', + 'RemoveProductFromProductSetRequest', + 'UpdateProductRequest', + 'UpdateProductSetRequest', + 'Block', + 'Page', + 'Paragraph', + 'Symbol', + 'TextAnnotation', + 'Word', + 'WebDetection', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/face.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/face.py index fecbfe028373..0d608f59c150 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/face.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/face.py @@ -19,12 +19,13 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "FaceRecognitionParams", - "Celebrity", - "FaceRecognitionResult", + 'FaceRecognitionParams', + 'Celebrity', + 'FaceRecognitionResult', }, ) @@ -86,10 +87,10 @@ class FaceRecognitionResult(proto.Message): Recognition confidence. Range [0, 1]. """ - celebrity: "Celebrity" = proto.Field( + celebrity: 'Celebrity' = proto.Field( proto.MESSAGE, number=1, - message="Celebrity", + message='Celebrity', ) confidence: float = proto.Field( proto.FLOAT, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/geometry.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/geometry.py index 88897bea5102..0398005bd403 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/geometry.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/geometry.py @@ -19,13 +19,14 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "Vertex", - "NormalizedVertex", - "BoundingPoly", - "Position", + 'Vertex', + 'NormalizedVertex', + 'BoundingPoly', + 'Position', }, ) @@ -84,15 +85,15 @@ class BoundingPoly(proto.Message): The bounding polygon normalized vertices. """ - vertices: MutableSequence["Vertex"] = proto.RepeatedField( + vertices: MutableSequence['Vertex'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Vertex", + message='Vertex', ) - normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( + normalized_vertices: MutableSequence['NormalizedVertex'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="NormalizedVertex", + message='NormalizedVertex', ) diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/image_annotator.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/image_annotator.py index a0a0cf215916..bcf0f829cdc9 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/image_annotator.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/image_annotator.py @@ -17,63 +17,62 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1p4beta1.types import face +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search +from google.cloud.vision_v1p4beta1.types import text_annotation +from google.cloud.vision_v1p4beta1.types import web_detection as gcv_web_detection from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.type import color_pb2 # type: ignore from google.type import latlng_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1p4beta1.types import ( - face, - geometry, - product_search, - text_annotation, -) -from google.cloud.vision_v1p4beta1.types import web_detection as gcv_web_detection __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "Likelihood", - "Feature", - "ImageSource", - "Image", - "FaceAnnotation", - "LocationInfo", - "Property", - "EntityAnnotation", - "LocalizedObjectAnnotation", - "SafeSearchAnnotation", - "LatLongRect", - "ColorInfo", - "DominantColorsAnnotation", - "ImageProperties", - "CropHint", - "CropHintsAnnotation", - "CropHintsParams", - "WebDetectionParams", - "TextDetectionParams", - "ImageContext", - "AnnotateImageRequest", - "ImageAnnotationContext", - "AnnotateImageResponse", - "BatchAnnotateImagesRequest", - "BatchAnnotateImagesResponse", - "AnnotateFileRequest", - "AnnotateFileResponse", - "BatchAnnotateFilesRequest", - "BatchAnnotateFilesResponse", - "AsyncAnnotateFileRequest", - "AsyncAnnotateFileResponse", - "AsyncBatchAnnotateImagesRequest", - "AsyncBatchAnnotateImagesResponse", - "AsyncBatchAnnotateFilesRequest", - "AsyncBatchAnnotateFilesResponse", - "InputConfig", - "OutputConfig", - "GcsSource", - "GcsDestination", - "OperationMetadata", + 'Likelihood', + 'Feature', + 'ImageSource', + 'Image', + 'FaceAnnotation', + 'LocationInfo', + 'Property', + 'EntityAnnotation', + 'LocalizedObjectAnnotation', + 'SafeSearchAnnotation', + 'LatLongRect', + 'ColorInfo', + 'DominantColorsAnnotation', + 'ImageProperties', + 'CropHint', + 'CropHintsAnnotation', + 'CropHintsParams', + 'WebDetectionParams', + 'TextDetectionParams', + 'ImageContext', + 'AnnotateImageRequest', + 'ImageAnnotationContext', + 'AnnotateImageResponse', + 'BatchAnnotateImagesRequest', + 'BatchAnnotateImagesResponse', + 'AnnotateFileRequest', + 'AnnotateFileResponse', + 'BatchAnnotateFilesRequest', + 'BatchAnnotateFilesResponse', + 'AsyncAnnotateFileRequest', + 'AsyncAnnotateFileResponse', + 'AsyncBatchAnnotateImagesRequest', + 'AsyncBatchAnnotateImagesResponse', + 'AsyncBatchAnnotateFilesRequest', + 'AsyncBatchAnnotateFilesResponse', + 'InputConfig', + 'OutputConfig', + 'GcsSource', + 'GcsDestination', + 'OperationMetadata', }, ) @@ -123,7 +122,6 @@ class Feature(proto.Message): ``TEXT_DETECTION`` also support "builtin/weekly" for the bleeding edge release updated weekly. """ - class Type(proto.Enum): r"""Type of Google Cloud Vision API feature to be extracted. @@ -255,10 +253,10 @@ class Image(proto.Message): proto.BYTES, number=1, ) - source: "ImageSource" = proto.Field( + source: 'ImageSource' = proto.Field( proto.MESSAGE, number=2, - message="ImageSource", + message='ImageSource', ) @@ -336,7 +334,6 @@ class Landmark(proto.Message): position (google.cloud.vision_v1p4beta1.types.Position): Face landmark position. """ - class Type(proto.Enum): r"""Face landmark (feature) type. Left and right are defined from the vantage of the viewer of the image without considering mirror @@ -452,10 +449,10 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_: "FaceAnnotation.Landmark.Type" = proto.Field( + type_: 'FaceAnnotation.Landmark.Type' = proto.Field( proto.ENUM, number=3, - enum="FaceAnnotation.Landmark.Type", + enum='FaceAnnotation.Landmark.Type', ) position: geometry.Position = proto.Field( proto.MESSAGE, @@ -498,44 +495,42 @@ class Type(proto.Enum): proto.FLOAT, number=8, ) - joy_likelihood: "Likelihood" = proto.Field( + joy_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) - sorrow_likelihood: "Likelihood" = proto.Field( + sorrow_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=10, - enum="Likelihood", + enum='Likelihood', ) - anger_likelihood: "Likelihood" = proto.Field( + anger_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=11, - enum="Likelihood", + enum='Likelihood', ) - surprise_likelihood: "Likelihood" = proto.Field( + surprise_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=12, - enum="Likelihood", + enum='Likelihood', ) - under_exposed_likelihood: "Likelihood" = proto.Field( + under_exposed_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=13, - enum="Likelihood", + enum='Likelihood', ) - blurred_likelihood: "Likelihood" = proto.Field( + blurred_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=14, - enum="Likelihood", + enum='Likelihood', ) - headwear_likelihood: "Likelihood" = proto.Field( + headwear_likelihood: 'Likelihood' = proto.Field( proto.ENUM, number=15, - enum="Likelihood", + enum='Likelihood', ) - recognition_result: MutableSequence[ - face.FaceRecognitionResult - ] = proto.RepeatedField( + recognition_result: MutableSequence[face.FaceRecognitionResult] = proto.RepeatedField( proto.MESSAGE, number=16, message=face.FaceRecognitionResult, @@ -657,15 +652,15 @@ class EntityAnnotation(proto.Message): number=7, message=geometry.BoundingPoly, ) - locations: MutableSequence["LocationInfo"] = proto.RepeatedField( + locations: MutableSequence['LocationInfo'] = proto.RepeatedField( proto.MESSAGE, number=8, - message="LocationInfo", + message='LocationInfo', ) - properties: MutableSequence["Property"] = proto.RepeatedField( + properties: MutableSequence['Property'] = proto.RepeatedField( proto.MESSAGE, number=9, - message="Property", + message='Property', ) @@ -741,30 +736,30 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult: "Likelihood" = proto.Field( + adult: 'Likelihood' = proto.Field( proto.ENUM, number=1, - enum="Likelihood", + enum='Likelihood', ) - spoof: "Likelihood" = proto.Field( + spoof: 'Likelihood' = proto.Field( proto.ENUM, number=2, - enum="Likelihood", + enum='Likelihood', ) - medical: "Likelihood" = proto.Field( + medical: 'Likelihood' = proto.Field( proto.ENUM, number=3, - enum="Likelihood", + enum='Likelihood', ) - violence: "Likelihood" = proto.Field( + violence: 'Likelihood' = proto.Field( proto.ENUM, number=4, - enum="Likelihood", + enum='Likelihood', ) - racy: "Likelihood" = proto.Field( + racy: 'Likelihood' = proto.Field( proto.ENUM, number=9, - enum="Likelihood", + enum='Likelihood', ) @@ -828,10 +823,10 @@ class DominantColorsAnnotation(proto.Message): fraction. """ - colors: MutableSequence["ColorInfo"] = proto.RepeatedField( + colors: MutableSequence['ColorInfo'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ColorInfo", + message='ColorInfo', ) @@ -844,10 +839,10 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors: "DominantColorsAnnotation" = proto.Field( + dominant_colors: 'DominantColorsAnnotation' = proto.Field( proto.MESSAGE, number=1, - message="DominantColorsAnnotation", + message='DominantColorsAnnotation', ) @@ -891,10 +886,10 @@ class CropHintsAnnotation(proto.Message): Crop hint results. """ - crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( + crop_hints: MutableSequence['CropHint'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="CropHint", + message='CropHint', ) @@ -988,19 +983,19 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect: "LatLongRect" = proto.Field( + lat_long_rect: 'LatLongRect' = proto.Field( proto.MESSAGE, number=1, - message="LatLongRect", + message='LatLongRect', ) language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params: "CropHintsParams" = proto.Field( + crop_hints_params: 'CropHintsParams' = proto.Field( proto.MESSAGE, number=4, - message="CropHintsParams", + message='CropHintsParams', ) face_recognition_params: face.FaceRecognitionParams = proto.Field( proto.MESSAGE, @@ -1012,15 +1007,15 @@ class ImageContext(proto.Message): number=5, message=product_search.ProductSearchParams, ) - web_detection_params: "WebDetectionParams" = proto.Field( + web_detection_params: 'WebDetectionParams' = proto.Field( proto.MESSAGE, number=6, - message="WebDetectionParams", + message='WebDetectionParams', ) - text_detection_params: "TextDetectionParams" = proto.Field( + text_detection_params: 'TextDetectionParams' = proto.Field( proto.MESSAGE, number=12, - message="TextDetectionParams", + message='TextDetectionParams', ) @@ -1039,20 +1034,20 @@ class AnnotateImageRequest(proto.Message): image. """ - image: "Image" = proto.Field( + image: 'Image' = proto.Field( proto.MESSAGE, number=1, - message="Image", + message='Image', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) @@ -1132,57 +1127,55 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( + face_annotations: MutableSequence['FaceAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="FaceAnnotation", + message='FaceAnnotation', ) - landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + landmark_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="EntityAnnotation", + message='EntityAnnotation', ) - logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + logo_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="EntityAnnotation", + message='EntityAnnotation', ) - label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + label_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="EntityAnnotation", + message='EntityAnnotation', ) - localized_object_annotations: MutableSequence[ - "LocalizedObjectAnnotation" - ] = proto.RepeatedField( + localized_object_annotations: MutableSequence['LocalizedObjectAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=22, - message="LocalizedObjectAnnotation", + message='LocalizedObjectAnnotation', ) - text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( + text_annotations: MutableSequence['EntityAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="EntityAnnotation", + message='EntityAnnotation', ) full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation: "SafeSearchAnnotation" = proto.Field( + safe_search_annotation: 'SafeSearchAnnotation' = proto.Field( proto.MESSAGE, number=6, - message="SafeSearchAnnotation", + message='SafeSearchAnnotation', ) - image_properties_annotation: "ImageProperties" = proto.Field( + image_properties_annotation: 'ImageProperties' = proto.Field( proto.MESSAGE, number=8, - message="ImageProperties", + message='ImageProperties', ) - crop_hints_annotation: "CropHintsAnnotation" = proto.Field( + crop_hints_annotation: 'CropHintsAnnotation' = proto.Field( proto.MESSAGE, number=11, - message="CropHintsAnnotation", + message='CropHintsAnnotation', ) web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, @@ -1199,10 +1192,10 @@ class AnnotateImageResponse(proto.Message): number=9, message=status_pb2.Status, ) - context: "ImageAnnotationContext" = proto.Field( + context: 'ImageAnnotationContext' = proto.Field( proto.MESSAGE, number=21, - message="ImageAnnotationContext", + message='ImageAnnotationContext', ) @@ -1216,10 +1209,10 @@ class BatchAnnotateImagesRequest(proto.Message): requests for this batch. """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) @@ -1232,10 +1225,10 @@ class BatchAnnotateImagesResponse(proto.Message): requests within the batch. """ - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) @@ -1271,20 +1264,20 @@ class AnnotateFileRequest(proto.Message): of the file. """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) pages: MutableSequence[int] = proto.RepeatedField( proto.INT32, @@ -1312,15 +1305,15 @@ class AnnotateFileResponse(proto.Message): The ``responses`` field will not be set in this case. """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateImageResponse'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="AnnotateImageResponse", + message='AnnotateImageResponse', ) total_pages: int = proto.Field( proto.INT32, @@ -1345,10 +1338,10 @@ class BatchAnnotateFilesRequest(proto.Message): BatchAnnotateFilesRequest. """ - requests: MutableSequence["AnnotateFileRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateFileRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateFileRequest", + message='AnnotateFileRequest', ) @@ -1363,10 +1356,10 @@ class BatchAnnotateFilesResponse(proto.Message): BatchAnnotateFilesRequest. """ - responses: MutableSequence["AnnotateFileResponse"] = proto.RepeatedField( + responses: MutableSequence['AnnotateFileResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateFileResponse", + message='AnnotateFileResponse', ) @@ -1386,25 +1379,25 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config: "InputConfig" = proto.Field( + input_config: 'InputConfig' = proto.Field( proto.MESSAGE, number=1, - message="InputConfig", + message='InputConfig', ) - features: MutableSequence["Feature"] = proto.RepeatedField( + features: MutableSequence['Feature'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="Feature", + message='Feature', ) - image_context: "ImageContext" = proto.Field( + image_context: 'ImageContext' = proto.Field( proto.MESSAGE, number=3, - message="ImageContext", + message='ImageContext', ) - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=4, - message="OutputConfig", + message='OutputConfig', ) @@ -1417,10 +1410,10 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=1, - message="OutputConfig", + message='OutputConfig', ) @@ -1436,15 +1429,15 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): metadata (e.g. format). """ - requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( + requests: MutableSequence['AnnotateImageRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AnnotateImageRequest", + message='AnnotateImageRequest', ) - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=2, - message="OutputConfig", + message='OutputConfig', ) @@ -1457,10 +1450,10 @@ class AsyncBatchAnnotateImagesResponse(proto.Message): AsyncBatchAnnotateImagesRequest. """ - output_config: "OutputConfig" = proto.Field( + output_config: 'OutputConfig' = proto.Field( proto.MESSAGE, number=1, - message="OutputConfig", + message='OutputConfig', ) @@ -1474,10 +1467,10 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): requests for this batch. """ - requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( + requests: MutableSequence['AsyncAnnotateFileRequest'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileRequest", + message='AsyncAnnotateFileRequest', ) @@ -1491,10 +1484,10 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): AsyncBatchAnnotateFilesRequest. """ - responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( + responses: MutableSequence['AsyncAnnotateFileResponse'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="AsyncAnnotateFileResponse", + message='AsyncAnnotateFileResponse', ) @@ -1519,10 +1512,10 @@ class InputConfig(proto.Message): are supported. Wildcards are not supported. """ - gcs_source: "GcsSource" = proto.Field( + gcs_source: 'GcsSource' = proto.Field( proto.MESSAGE, number=1, - message="GcsSource", + message='GcsSource', ) content: bytes = proto.Field( proto.BYTES, @@ -1555,10 +1548,10 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination: "GcsDestination" = proto.Field( + gcs_destination: 'GcsDestination' = proto.Field( proto.MESSAGE, number=1, - message="GcsDestination", + message='GcsDestination', ) batch_size: int = proto.Field( proto.INT32, @@ -1599,16 +1592,16 @@ class GcsDestination(proto.Message): Examples: - - File Prefix: gs://bucket-name/here/filenameprefix The - output files will be created in gs://bucket-name/here/ and - the names of the output files will begin with - "filenameprefix". + - File Prefix: gs://bucket-name/here/filenameprefix The + output files will be created in gs://bucket-name/here/ + and the names of the output files will begin with + "filenameprefix". - - Directory Prefix: gs://bucket-name/some/location/ The - output files will be created in - gs://bucket-name/some/location/ and the names of the - output files could be anything because there was no - filename prefix specified. + - Directory Prefix: gs://bucket-name/some/location/ The + output files will be created in + gs://bucket-name/some/location/ and the names of the + output files could be anything because there was no + filename prefix specified. If multiple outputs, each response is still AnnotateFileResponse, each of which contains some subset of @@ -1635,7 +1628,6 @@ class OperationMetadata(proto.Message): The time when the operation result was last updated. """ - class State(proto.Enum): r"""Batch operation states. diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search.py index 1d5fb1d412b1..2ef087ee72a9 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search.py @@ -17,16 +17,18 @@ from typing import MutableMapping, MutableSequence -from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.vision_v1p4beta1.types import geometry, product_search_service +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.protobuf import timestamp_pb2 # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "ProductSearchParams", - "ProductSearchResults", + 'ProductSearchParams', + 'ProductSearchResults', }, ) @@ -194,17 +196,15 @@ class GroupedResult(proto.Message): number=1, message=geometry.BoundingPoly, ) - results: MutableSequence["ProductSearchResults.Result"] = proto.RepeatedField( + results: MutableSequence['ProductSearchResults.Result'] = proto.RepeatedField( proto.MESSAGE, number=2, - message="ProductSearchResults.Result", + message='ProductSearchResults.Result', ) - object_annotations: MutableSequence[ - "ProductSearchResults.ObjectAnnotation" - ] = proto.RepeatedField( + object_annotations: MutableSequence['ProductSearchResults.ObjectAnnotation'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="ProductSearchResults.ObjectAnnotation", + message='ProductSearchResults.ObjectAnnotation', ) index_time: timestamp_pb2.Timestamp = proto.Field( diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search_service.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search_service.py index e2d1875066cc..7f5daeb43e57 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search_service.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/product_search_service.py @@ -17,47 +17,48 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + +from google.cloud.vision_v1p4beta1.types import geometry from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore -import proto # type: ignore -from google.cloud.vision_v1p4beta1.types import geometry __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "Product", - "ProductSet", - "ReferenceImage", - "CreateProductRequest", - "ListProductsRequest", - "ListProductsResponse", - "GetProductRequest", - "UpdateProductRequest", - "DeleteProductRequest", - "CreateProductSetRequest", - "ListProductSetsRequest", - "ListProductSetsResponse", - "GetProductSetRequest", - "UpdateProductSetRequest", - "DeleteProductSetRequest", - "CreateReferenceImageRequest", - "ListReferenceImagesRequest", - "ListReferenceImagesResponse", - "GetReferenceImageRequest", - "DeleteReferenceImageRequest", - "AddProductToProductSetRequest", - "RemoveProductFromProductSetRequest", - "ListProductsInProductSetRequest", - "ListProductsInProductSetResponse", - "ImportProductSetsGcsSource", - "ImportProductSetsInputConfig", - "ImportProductSetsRequest", - "ImportProductSetsResponse", - "BatchOperationMetadata", - "ProductSetPurgeConfig", - "PurgeProductsRequest", + 'Product', + 'ProductSet', + 'ReferenceImage', + 'CreateProductRequest', + 'ListProductsRequest', + 'ListProductsResponse', + 'GetProductRequest', + 'UpdateProductRequest', + 'DeleteProductRequest', + 'CreateProductSetRequest', + 'ListProductSetsRequest', + 'ListProductSetsResponse', + 'GetProductSetRequest', + 'UpdateProductSetRequest', + 'DeleteProductSetRequest', + 'CreateReferenceImageRequest', + 'ListReferenceImagesRequest', + 'ListReferenceImagesResponse', + 'GetReferenceImageRequest', + 'DeleteReferenceImageRequest', + 'AddProductToProductSetRequest', + 'RemoveProductFromProductSetRequest', + 'ListProductsInProductSetRequest', + 'ListProductsInProductSetResponse', + 'ImportProductSetsGcsSource', + 'ImportProductSetsInputConfig', + 'ImportProductSetsRequest', + 'ImportProductSetsResponse', + 'BatchOperationMetadata', + 'ProductSetPurgeConfig', + 'PurgeProductsRequest', }, ) @@ -276,10 +277,10 @@ class CreateProductRequest(proto.Message): proto.STRING, number=1, ) - product: "Product" = proto.Field( + product: 'Product' = proto.Field( proto.MESSAGE, number=2, - message="Product", + message='Product', ) product_id: str = proto.Field( proto.STRING, @@ -334,10 +335,10 @@ class ListProductsResponse(proto.Message): def raw_page(self): return self - products: MutableSequence["Product"] = proto.RepeatedField( + products: MutableSequence['Product'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Product", + message='Product', ) next_page_token: str = proto.Field( proto.STRING, @@ -377,10 +378,10 @@ class UpdateProductRequest(proto.Message): ``product_labels``, ``display_name``, and ``description``. """ - product: "Product" = proto.Field( + product: 'Product' = proto.Field( proto.MESSAGE, number=1, - message="Product", + message='Product', ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -429,10 +430,10 @@ class CreateProductSetRequest(proto.Message): proto.STRING, number=1, ) - product_set: "ProductSet" = proto.Field( + product_set: 'ProductSet' = proto.Field( proto.MESSAGE, number=2, - message="ProductSet", + message='ProductSet', ) product_set_id: str = proto.Field( proto.STRING, @@ -487,10 +488,10 @@ class ListProductSetsResponse(proto.Message): def raw_page(self): return self - product_sets: MutableSequence["ProductSet"] = proto.RepeatedField( + product_sets: MutableSequence['ProductSet'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ProductSet", + message='ProductSet', ) next_page_token: str = proto.Field( proto.STRING, @@ -529,10 +530,10 @@ class UpdateProductSetRequest(proto.Message): ``display_name``. """ - product_set: "ProductSet" = proto.Field( + product_set: 'ProductSet' = proto.Field( proto.MESSAGE, number=1, - message="ProductSet", + message='ProductSet', ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -583,10 +584,10 @@ class CreateReferenceImageRequest(proto.Message): proto.STRING, number=1, ) - reference_image: "ReferenceImage" = proto.Field( + reference_image: 'ReferenceImage' = proto.Field( proto.MESSAGE, number=2, - message="ReferenceImage", + message='ReferenceImage', ) reference_image_id: str = proto.Field( proto.STRING, @@ -647,10 +648,10 @@ class ListReferenceImagesResponse(proto.Message): def raw_page(self): return self - reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( + reference_images: MutableSequence['ReferenceImage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ReferenceImage", + message='ReferenceImage', ) page_size: int = proto.Field( proto.INT32, @@ -801,10 +802,10 @@ class ListProductsInProductSetResponse(proto.Message): def raw_page(self): return self - products: MutableSequence["Product"] = proto.RepeatedField( + products: MutableSequence['Product'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Product", + message='Product', ) next_page_token: str = proto.Field( proto.STRING, @@ -913,11 +914,11 @@ class ImportProductSetsInputConfig(proto.Message): This field is a member of `oneof`_ ``source``. """ - gcs_source: "ImportProductSetsGcsSource" = proto.Field( + gcs_source: 'ImportProductSetsGcsSource' = proto.Field( proto.MESSAGE, number=1, - oneof="source", - message="ImportProductSetsGcsSource", + oneof='source', + message='ImportProductSetsGcsSource', ) @@ -939,10 +940,10 @@ class ImportProductSetsRequest(proto.Message): proto.STRING, number=1, ) - input_config: "ImportProductSetsInputConfig" = proto.Field( + input_config: 'ImportProductSetsInputConfig' = proto.Field( proto.MESSAGE, number=2, - message="ImportProductSetsInputConfig", + message='ImportProductSetsInputConfig', ) @@ -968,10 +969,10 @@ class ImportProductSetsResponse(proto.Message): line 0. """ - reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( + reference_images: MutableSequence['ReferenceImage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="ReferenceImage", + message='ReferenceImage', ) statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, @@ -998,7 +999,6 @@ class BatchOperationMetadata(proto.Message): [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. """ - class State(proto.Enum): r"""Enumerates the possible states that the batch request can be in. @@ -1092,16 +1092,16 @@ class PurgeProductsRequest(proto.Message): value to true to actually perform the purge. """ - product_set_purge_config: "ProductSetPurgeConfig" = proto.Field( + product_set_purge_config: 'ProductSetPurgeConfig' = proto.Field( proto.MESSAGE, number=2, - oneof="target", - message="ProductSetPurgeConfig", + oneof='target', + message='ProductSetPurgeConfig', ) delete_orphan_products: bool = proto.Field( proto.BOOL, number=3, - oneof="target", + oneof='target', ) parent: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/text_annotation.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/text_annotation.py index 8ff74951cbad..3135ade64f50 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/text_annotation.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/text_annotation.py @@ -21,15 +21,16 @@ from google.cloud.vision_v1p4beta1.types import geometry + __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "TextAnnotation", - "Page", - "Block", - "Paragraph", - "Word", - "Symbol", + 'TextAnnotation', + 'Page', + 'Block', + 'Paragraph', + 'Word', + 'Symbol', }, ) @@ -81,7 +82,6 @@ class DetectedBreak(proto.Message): is_prefix (bool): True if break prepends the element. """ - class BreakType(proto.Enum): r"""Enum to denote the type of break found. New line, space etc. @@ -108,10 +108,10 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( + type_: 'TextAnnotation.DetectedBreak.BreakType' = proto.Field( proto.ENUM, number=1, - enum="TextAnnotation.DetectedBreak.BreakType", + enum='TextAnnotation.DetectedBreak.BreakType', ) is_prefix: bool = proto.Field( proto.BOOL, @@ -129,23 +129,21 @@ class TextProperty(proto.Message): Detected start or end of a text segment. """ - detected_languages: MutableSequence[ - "TextAnnotation.DetectedLanguage" - ] = proto.RepeatedField( + detected_languages: MutableSequence['TextAnnotation.DetectedLanguage'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="TextAnnotation.DetectedLanguage", + message='TextAnnotation.DetectedLanguage', ) - detected_break: "TextAnnotation.DetectedBreak" = proto.Field( + detected_break: 'TextAnnotation.DetectedBreak' = proto.Field( proto.MESSAGE, number=2, - message="TextAnnotation.DetectedBreak", + message='TextAnnotation.DetectedBreak', ) - pages: MutableSequence["Page"] = proto.RepeatedField( + pages: MutableSequence['Page'] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Page", + message='Page', ) text: str = proto.Field( proto.STRING, @@ -172,10 +170,10 @@ class Page(proto.Message): Confidence of the OCR results on the page. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) width: int = proto.Field( proto.INT32, @@ -185,10 +183,10 @@ class Page(proto.Message): proto.INT32, number=3, ) - blocks: MutableSequence["Block"] = proto.RepeatedField( + blocks: MutableSequence['Block'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="Block", + message='Block', ) confidence: float = proto.Field( proto.FLOAT, @@ -210,24 +208,24 @@ class Block(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: + - when the text is horizontal it might look like: - :: + :: - 0----1 - | | - 3----2 + 0----1 + | | + 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: + - when it's rotated 180 degrees around the top-left corner + it becomes: - :: + :: - 2----3 - | | - 1----0 + 2----3 + | | + 1----0 - and the vertex order will still be (0, 1, 2, 3). + and the vertex order will still be (0, 1, 2, 3). paragraphs (MutableSequence[google.cloud.vision_v1p4beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). @@ -237,7 +235,6 @@ class Block(proto.Message): confidence (float): Confidence of the OCR results on the block. Range [0, 1]. """ - class BlockType(proto.Enum): r"""Type of a block (text, image etc) as identified by OCR. @@ -262,20 +259,20 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( + paragraphs: MutableSequence['Paragraph'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Paragraph", + message='Paragraph', ) block_type: BlockType = proto.Field( proto.ENUM, @@ -303,11 +300,11 @@ class Paragraph(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertex order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). words (MutableSequence[google.cloud.vision_v1p4beta1.types.Word]): List of all words in this paragraph. confidence (float): @@ -315,20 +312,20 @@ class Paragraph(proto.Message): 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words: MutableSequence["Word"] = proto.RepeatedField( + words: MutableSequence['Word'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Word", + message='Word', ) confidence: float = proto.Field( proto.FLOAT, @@ -349,11 +346,11 @@ class Word(proto.Message): represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertex order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). symbols (MutableSequence[google.cloud.vision_v1p4beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural @@ -362,20 +359,20 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols: MutableSequence["Symbol"] = proto.RepeatedField( + symbols: MutableSequence['Symbol'] = proto.RepeatedField( proto.MESSAGE, number=3, - message="Symbol", + message='Symbol', ) confidence: float = proto.Field( proto.FLOAT, @@ -397,11 +394,11 @@ class Symbol(proto.Message): is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - - when the text is horizontal it might look like: 0----1 \| - \| 3----2 - - when it's rotated 180 degrees around the top-left corner - it becomes: 2----3 \| \| 1----0 and the vertex order will - still be (0, 1, 2, 3). + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). text (str): The actual UTF-8 representation of the symbol. @@ -409,10 +406,10 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property: "TextAnnotation.TextProperty" = proto.Field( + property: 'TextAnnotation.TextProperty' = proto.Field( proto.MESSAGE, number=1, - message="TextAnnotation.TextProperty", + message='TextAnnotation.TextProperty', ) bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/web_detection.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/web_detection.py index 3bfadec02406..e498481b45e8 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/web_detection.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/types/web_detection.py @@ -19,10 +19,11 @@ import proto # type: ignore + __protobuf__ = proto.module( - package="google.cloud.vision.v1p4beta1", + package='google.cloud.vision.v1p4beta1', manifest={ - "WebDetection", + 'WebDetection', }, ) @@ -137,19 +138,15 @@ class WebPage(proto.Message): proto.STRING, number=3, ) - full_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + full_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=4, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) - partial_matching_images: MutableSequence[ - "WebDetection.WebImage" - ] = proto.RepeatedField( + partial_matching_images: MutableSequence['WebDetection.WebImage'] = proto.RepeatedField( proto.MESSAGE, number=5, - message="WebDetection.WebImage", + message='WebDetection.WebImage', ) class WebLabel(proto.Message): diff --git a/packages/google-cloud-vision/mypy.ini b/packages/google-cloud-vision/mypy.ini index 574c5aed394b..a3cb5c292172 100644 --- a/packages/google-cloud-vision/mypy.ini +++ b/packages/google-cloud-vision/mypy.ini @@ -1,3 +1,3 @@ [mypy] -python_version = 3.7 +python_version = 3.14 namespace_packages = True diff --git a/packages/google-cloud-vision/noxfile.py b/packages/google-cloud-vision/noxfile.py index 59ceb95f779f..f373cdbeff48 100644 --- a/packages/google-cloud-vision/noxfile.py +++ b/packages/google-cloud-vision/noxfile.py @@ -17,6 +17,7 @@ import pathlib import re import shutil + from typing import Dict, List import warnings @@ -234,12 +235,7 @@ def unit(session, protobuf_implementation): # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): # Remove this check once support for Protobuf 3.x is dropped. - if protobuf_implementation == "cpp" and session.python in ( - "3.11", - "3.12", - "3.13", - "3.14", - ): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13", "3.14"): session.skip("cpp implementation is not supported in python 3.11+") constraints_path = str( @@ -381,10 +377,8 @@ def docs(session): "-W", # warnings as errors "-T", # show full traceback on exception "-N", # no colors - "-b", - "html", # builder - "-d", - os.path.join("docs", "_build", "doctrees", ""), # cache directory + "-b", "html", # builder + "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory # paths to build: os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), @@ -452,12 +446,7 @@ def prerelease_deps(session, protobuf_implementation): # TODO(https://github.com/googleapis/gapic-generator-python/issues/2388): # Remove this check once support for Protobuf 3.x is dropped. - if protobuf_implementation == "cpp" and session.python in ( - "3.11", - "3.12", - "3.13", - "3.14", - ): + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13", "3.14"): session.skip("cpp implementation is not supported in python 3.11+") # Install all dependencies diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py index 0288fce2c8fc..f3def6d8a848 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py @@ -39,7 +39,8 @@ async def sample_async_batch_annotate_files(): client = vision_v1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1.AsyncBatchAnnotateFilesRequest() + request = vision_v1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ async def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_sync.py index 69d7b28f84a1..de2447c2a8fe 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_sync.py @@ -39,7 +39,8 @@ def sample_async_batch_annotate_files(): client = vision_v1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1.AsyncBatchAnnotateFilesRequest() + request = vision_v1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py index 0953c8f53139..2d9a97969eb2 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_async_batch_annotate_images(): client = vision_v1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1.AsyncBatchAnnotateImagesRequest() + request = vision_v1.AsyncBatchAnnotateImagesRequest( + ) # Make the request operation = client.async_batch_annotate_images(request=request) @@ -51,5 +52,4 @@ async def sample_async_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_AsyncBatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_sync.py index 733d4a9d8038..9a6cff5be93a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_async_batch_annotate_images(): client = vision_v1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1.AsyncBatchAnnotateImagesRequest() + request = vision_v1.AsyncBatchAnnotateImagesRequest( + ) # Make the request operation = client.async_batch_annotate_images(request=request) @@ -51,5 +52,4 @@ def sample_async_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_AsyncBatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_async.py index f7785337c20e..a98771906e5a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_files(): client = vision_v1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1.BatchAnnotateFilesRequest() + request = vision_v1.BatchAnnotateFilesRequest( + ) # Make the request response = await client.batch_annotate_files(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_BatchAnnotateFiles_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_sync.py index c00c4f7c981e..388248aad182 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_files_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_files(): client = vision_v1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1.BatchAnnotateFilesRequest() + request = vision_v1.BatchAnnotateFilesRequest( + ) # Make the request response = client.batch_annotate_files(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_BatchAnnotateFiles_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_async.py index 8e954c205482..89d7fbd9de7b 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_images(): client = vision_v1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1.BatchAnnotateImagesRequest() + request = vision_v1.BatchAnnotateImagesRequest( + ) # Make the request response = await client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_BatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_sync.py index 82496a957f6e..39b49ed9eba9 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_image_annotator_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_images(): client = vision_v1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1.BatchAnnotateImagesRequest() + request = vision_v1.BatchAnnotateImagesRequest( + ) # Make the request response = client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1_generated_ImageAnnotator_BatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_async.py index 37a13e8c63cf..e2f26851b314 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_async.py @@ -49,5 +49,4 @@ async def sample_create_product(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_CreateProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_async.py index c8e77ef1c3b5..93f2df7c8691 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_async.py @@ -49,5 +49,4 @@ async def sample_create_product_set(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_CreateProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_sync.py index 3fb2f196e0b9..14073be246f6 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_set_sync.py @@ -49,5 +49,4 @@ def sample_create_product_set(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_CreateProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_sync.py index 4e68449e5ccc..bb444ccffa59 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_product_sync.py @@ -49,5 +49,4 @@ def sample_create_product(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_CreateProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_async.py index 61f9918aa32f..2d683ddbb966 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_async.py @@ -53,5 +53,4 @@ async def sample_create_reference_image(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_CreateReferenceImage_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_sync.py index 12f53ed37d19..8253f237c1b0 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_create_reference_image_sync.py @@ -53,5 +53,4 @@ def sample_create_reference_image(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_CreateReferenceImage_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_async.py index 85877a0f73d1..d0e81b425a56 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_async.py @@ -49,5 +49,4 @@ async def sample_get_product(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_GetProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_async.py index 88a185f1a738..983b799ecd47 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_async.py @@ -49,5 +49,4 @@ async def sample_get_product_set(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_GetProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_sync.py index 6d86f30a915d..9cdd62a6fb07 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_set_sync.py @@ -49,5 +49,4 @@ def sample_get_product_set(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_GetProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_sync.py index 839ee8e094ca..acbac5597910 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_product_sync.py @@ -49,5 +49,4 @@ def sample_get_product(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_GetProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_async.py index ebbd0372e956..817cde577530 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_async.py @@ -49,5 +49,4 @@ async def sample_get_reference_image(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_GetReferenceImage_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_sync.py index 243d179ab5f8..f73c4b6c2bbe 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_get_reference_image_sync.py @@ -49,5 +49,4 @@ def sample_get_reference_image(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_GetReferenceImage_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py index eab3bcbdcff0..459bdf6d2e94 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py @@ -53,5 +53,4 @@ async def sample_import_product_sets(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_ImportProductSets_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_sync.py index 1c9153cdf335..4026a22a36bc 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_sync.py @@ -53,5 +53,4 @@ def sample_import_product_sets(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_ImportProductSets_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_async.py index 2172dba436f8..3bedd600822f 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_async.py @@ -50,5 +50,4 @@ async def sample_list_product_sets(): async for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListProductSets_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_sync.py index 11973b8bf9cc..372d9c38f61a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_product_sets_sync.py @@ -50,5 +50,4 @@ def sample_list_product_sets(): for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListProductSets_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_async.py index 5d01dd759a46..5e6870d384c5 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_async.py @@ -50,5 +50,4 @@ async def sample_list_products(): async for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListProducts_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_async.py index 69da0f8447be..45f6792fd347 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_async.py @@ -50,5 +50,4 @@ async def sample_list_products_in_product_set(): async for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListProductsInProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_sync.py index a3e44d58066a..83949638d156 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_in_product_set_sync.py @@ -50,5 +50,4 @@ def sample_list_products_in_product_set(): for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListProductsInProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_sync.py index aacef907ce94..01fd951f33a6 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_products_sync.py @@ -50,5 +50,4 @@ def sample_list_products(): for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListProducts_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_async.py index 944f893f07ca..a414f0986055 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_async.py @@ -50,5 +50,4 @@ async def sample_list_reference_images(): async for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListReferenceImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_sync.py index e393e657677f..5cf682f4967c 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_list_reference_images_sync.py @@ -50,5 +50,4 @@ def sample_list_reference_images(): for response in page_result: print(response) - # [END vision_v1_generated_ProductSearch_ListReferenceImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py index 695f670055e3..b178521747d7 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py @@ -53,5 +53,4 @@ async def sample_purge_products(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_PurgeProducts_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_sync.py index 384e392c2834..b7b1f8a4ced1 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_purge_products_sync.py @@ -53,5 +53,4 @@ def sample_purge_products(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_PurgeProducts_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_async.py index 6845e6296769..dd40134fb385 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_async.py @@ -39,7 +39,8 @@ async def sample_update_product(): client = vision_v1.ProductSearchAsyncClient() # Initialize request argument(s) - request = vision_v1.UpdateProductRequest() + request = vision_v1.UpdateProductRequest( + ) # Make the request response = await client.update_product(request=request) @@ -47,5 +48,4 @@ async def sample_update_product(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_UpdateProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_async.py index 4b728ede4467..dfe4103bc0cd 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_async.py @@ -39,7 +39,8 @@ async def sample_update_product_set(): client = vision_v1.ProductSearchAsyncClient() # Initialize request argument(s) - request = vision_v1.UpdateProductSetRequest() + request = vision_v1.UpdateProductSetRequest( + ) # Make the request response = await client.update_product_set(request=request) @@ -47,5 +48,4 @@ async def sample_update_product_set(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_UpdateProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_sync.py index eaf00bbbfd30..1ee6b448db3b 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_set_sync.py @@ -39,7 +39,8 @@ def sample_update_product_set(): client = vision_v1.ProductSearchClient() # Initialize request argument(s) - request = vision_v1.UpdateProductSetRequest() + request = vision_v1.UpdateProductSetRequest( + ) # Make the request response = client.update_product_set(request=request) @@ -47,5 +48,4 @@ def sample_update_product_set(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_UpdateProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_sync.py index a875ca703bf5..bd783b3e37ff 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1_generated_product_search_update_product_sync.py @@ -39,7 +39,8 @@ def sample_update_product(): client = vision_v1.ProductSearchClient() # Initialize request argument(s) - request = vision_v1.UpdateProductRequest() + request = vision_v1.UpdateProductRequest( + ) # Make the request response = client.update_product(request=request) @@ -47,5 +48,4 @@ def sample_update_product(): # Handle the response print(response) - # [END vision_v1_generated_ProductSearch_UpdateProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_async.py index acd99ea568a6..d879bd5f1486 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_images(): client = vision_v1p1beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p1beta1.BatchAnnotateImagesRequest() + request = vision_v1p1beta1.BatchAnnotateImagesRequest( + ) # Make the request response = await client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p1beta1_generated_ImageAnnotator_BatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_sync.py index 60823bc4200a..dd08e70b8088 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p1beta1_generated_image_annotator_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_images(): client = vision_v1p1beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p1beta1.BatchAnnotateImagesRequest() + request = vision_v1p1beta1.BatchAnnotateImagesRequest( + ) # Make the request response = client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p1beta1_generated_ImageAnnotator_BatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py index 8fd90858a501..40ac1ed44fd2 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py @@ -39,7 +39,8 @@ async def sample_async_batch_annotate_files(): client = vision_v1p2beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p2beta1.AsyncBatchAnnotateFilesRequest() + request = vision_v1p2beta1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ async def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p2beta1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_sync.py index 3ca6fbfedbef..c1de8241c32c 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_sync.py @@ -39,7 +39,8 @@ def sample_async_batch_annotate_files(): client = vision_v1p2beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p2beta1.AsyncBatchAnnotateFilesRequest() + request = vision_v1p2beta1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p2beta1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_async.py index e54c5da9ab67..5c4ddc3d8034 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_images(): client = vision_v1p2beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p2beta1.BatchAnnotateImagesRequest() + request = vision_v1p2beta1.BatchAnnotateImagesRequest( + ) # Make the request response = await client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p2beta1_generated_ImageAnnotator_BatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_sync.py index c0d489c5a1b6..a58f396f7342 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_images(): client = vision_v1p2beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p2beta1.BatchAnnotateImagesRequest() + request = vision_v1p2beta1.BatchAnnotateImagesRequest( + ) # Make the request response = client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p2beta1_generated_ImageAnnotator_BatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py index fd876fdee2d4..5190f7742e0d 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py @@ -39,7 +39,8 @@ async def sample_async_batch_annotate_files(): client = vision_v1p3beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p3beta1.AsyncBatchAnnotateFilesRequest() + request = vision_v1p3beta1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ async def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_sync.py index a75fe8d24abd..f483c5009cb8 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_sync.py @@ -39,7 +39,8 @@ def sample_async_batch_annotate_files(): client = vision_v1p3beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p3beta1.AsyncBatchAnnotateFilesRequest() + request = vision_v1p3beta1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_async.py index 980431b148bf..b22f3e3151f2 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_images(): client = vision_v1p3beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p3beta1.BatchAnnotateImagesRequest() + request = vision_v1p3beta1.BatchAnnotateImagesRequest( + ) # Make the request response = await client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ImageAnnotator_BatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_sync.py index e8e7d0842423..8c9ffba0b6d8 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_images(): client = vision_v1p3beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p3beta1.BatchAnnotateImagesRequest() + request = vision_v1p3beta1.BatchAnnotateImagesRequest( + ) # Make the request response = client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ImageAnnotator_BatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_async.py index 220c7ea2cbcc..793cce5a0ef0 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_async.py @@ -49,5 +49,4 @@ async def sample_create_product(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_CreateProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_async.py index e7af9492b37b..3be0b86872d8 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_async.py @@ -49,5 +49,4 @@ async def sample_create_product_set(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_CreateProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_sync.py index bdf9bfe3b75f..3203642ba373 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_set_sync.py @@ -49,5 +49,4 @@ def sample_create_product_set(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_CreateProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_sync.py index 50e2025b7130..d123455da9ec 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_product_sync.py @@ -49,5 +49,4 @@ def sample_create_product(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_CreateProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_async.py index 81b6b961d184..dd6b1af2bcb7 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_async.py @@ -53,5 +53,4 @@ async def sample_create_reference_image(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_CreateReferenceImage_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_sync.py index d4074bc1f7e3..7b58c06580dd 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_create_reference_image_sync.py @@ -53,5 +53,4 @@ def sample_create_reference_image(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_CreateReferenceImage_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_async.py index e67b99a12ac1..17f5701d3ad9 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_async.py @@ -49,5 +49,4 @@ async def sample_get_product(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_GetProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_async.py index 567e5add9ac4..f1757a7f16b5 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_async.py @@ -49,5 +49,4 @@ async def sample_get_product_set(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_GetProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_sync.py index 7b6742a7ea97..db13afceab6e 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_set_sync.py @@ -49,5 +49,4 @@ def sample_get_product_set(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_GetProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_sync.py index 6616a3d5b504..c70f38e8a948 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_product_sync.py @@ -49,5 +49,4 @@ def sample_get_product(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_GetProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_async.py index 9cc4a0f99c2e..877f916e674f 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_async.py @@ -49,5 +49,4 @@ async def sample_get_reference_image(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_GetReferenceImage_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_sync.py index 44adc6cdea65..42a91a21ce71 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_get_reference_image_sync.py @@ -49,5 +49,4 @@ def sample_get_reference_image(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_GetReferenceImage_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py index 1b8904dbad18..407fbfb7f661 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py @@ -53,5 +53,4 @@ async def sample_import_product_sets(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ImportProductSets_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_sync.py index ea7c0abfd4ff..4c5c11dc7fba 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_sync.py @@ -53,5 +53,4 @@ def sample_import_product_sets(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ImportProductSets_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_async.py index e42da64d36ae..df0996ae9456 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_async.py @@ -50,5 +50,4 @@ async def sample_list_product_sets(): async for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListProductSets_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_sync.py index 69559636904e..c234309dbedf 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_product_sets_sync.py @@ -50,5 +50,4 @@ def sample_list_product_sets(): for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListProductSets_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_async.py index 5cd13cb20fb4..2c468270578d 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_async.py @@ -50,5 +50,4 @@ async def sample_list_products(): async for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListProducts_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_async.py index 300599e5b37b..47c84c5e3d34 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_async.py @@ -50,5 +50,4 @@ async def sample_list_products_in_product_set(): async for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListProductsInProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_sync.py index 27305c8cf0bb..9131b0695a1d 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_in_product_set_sync.py @@ -50,5 +50,4 @@ def sample_list_products_in_product_set(): for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListProductsInProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_sync.py index 292020a7eb3e..8fa1334c17e6 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_products_sync.py @@ -50,5 +50,4 @@ def sample_list_products(): for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListProducts_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_async.py index f5ecc632e342..e30b29e9dba4 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_async.py @@ -50,5 +50,4 @@ async def sample_list_reference_images(): async for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListReferenceImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_sync.py index 5108742a8d7b..6a6c66192b95 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_list_reference_images_sync.py @@ -50,5 +50,4 @@ def sample_list_reference_images(): for response in page_result: print(response) - # [END vision_v1p3beta1_generated_ProductSearch_ListReferenceImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_async.py index 6e9670077ae5..ee3f4f9e33ab 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_async.py @@ -39,7 +39,8 @@ async def sample_update_product(): client = vision_v1p3beta1.ProductSearchAsyncClient() # Initialize request argument(s) - request = vision_v1p3beta1.UpdateProductRequest() + request = vision_v1p3beta1.UpdateProductRequest( + ) # Make the request response = await client.update_product(request=request) @@ -47,5 +48,4 @@ async def sample_update_product(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_UpdateProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_async.py index afa8692ccf66..51c68973f1bd 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_async.py @@ -39,7 +39,8 @@ async def sample_update_product_set(): client = vision_v1p3beta1.ProductSearchAsyncClient() # Initialize request argument(s) - request = vision_v1p3beta1.UpdateProductSetRequest() + request = vision_v1p3beta1.UpdateProductSetRequest( + ) # Make the request response = await client.update_product_set(request=request) @@ -47,5 +48,4 @@ async def sample_update_product_set(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_UpdateProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_sync.py index 3e3f7d9bdb2c..11ff73a9c47c 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_set_sync.py @@ -39,7 +39,8 @@ def sample_update_product_set(): client = vision_v1p3beta1.ProductSearchClient() # Initialize request argument(s) - request = vision_v1p3beta1.UpdateProductSetRequest() + request = vision_v1p3beta1.UpdateProductSetRequest( + ) # Make the request response = client.update_product_set(request=request) @@ -47,5 +48,4 @@ def sample_update_product_set(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_UpdateProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_sync.py index be91ff8ceeff..c4f54cac9ad2 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p3beta1_generated_product_search_update_product_sync.py @@ -39,7 +39,8 @@ def sample_update_product(): client = vision_v1p3beta1.ProductSearchClient() # Initialize request argument(s) - request = vision_v1p3beta1.UpdateProductRequest() + request = vision_v1p3beta1.UpdateProductRequest( + ) # Make the request response = client.update_product(request=request) @@ -47,5 +48,4 @@ def sample_update_product(): # Handle the response print(response) - # [END vision_v1p3beta1_generated_ProductSearch_UpdateProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py index e05ddd963c6e..829a0e5a2a09 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py @@ -39,7 +39,8 @@ async def sample_async_batch_annotate_files(): client = vision_v1p4beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p4beta1.AsyncBatchAnnotateFilesRequest() + request = vision_v1p4beta1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ async def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_sync.py index 67074625a366..1240a921b67a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_sync.py @@ -39,7 +39,8 @@ def sample_async_batch_annotate_files(): client = vision_v1p4beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p4beta1.AsyncBatchAnnotateFilesRequest() + request = vision_v1p4beta1.AsyncBatchAnnotateFilesRequest( + ) # Make the request operation = client.async_batch_annotate_files(request=request) @@ -51,5 +52,4 @@ def sample_async_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_AsyncBatchAnnotateFiles_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py index 341975808b5f..6a1cc369ba00 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_async_batch_annotate_images(): client = vision_v1p4beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p4beta1.AsyncBatchAnnotateImagesRequest() + request = vision_v1p4beta1.AsyncBatchAnnotateImagesRequest( + ) # Make the request operation = client.async_batch_annotate_images(request=request) @@ -51,5 +52,4 @@ async def sample_async_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_AsyncBatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_sync.py index 54637091a18d..6743a6ef532b 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_async_batch_annotate_images(): client = vision_v1p4beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p4beta1.AsyncBatchAnnotateImagesRequest() + request = vision_v1p4beta1.AsyncBatchAnnotateImagesRequest( + ) # Make the request operation = client.async_batch_annotate_images(request=request) @@ -51,5 +52,4 @@ def sample_async_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_AsyncBatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_async.py index c98b1223966f..4de0bb3dd716 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_files(): client = vision_v1p4beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p4beta1.BatchAnnotateFilesRequest() + request = vision_v1p4beta1.BatchAnnotateFilesRequest( + ) # Make the request response = await client.batch_annotate_files(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_BatchAnnotateFiles_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_sync.py index 37f31b2c5c4e..fc3f66d1a36a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_files_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_files(): client = vision_v1p4beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p4beta1.BatchAnnotateFilesRequest() + request = vision_v1p4beta1.BatchAnnotateFilesRequest( + ) # Make the request response = client.batch_annotate_files(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_files(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_BatchAnnotateFiles_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_async.py index 11d539a96efc..8621cc3b9391 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_async.py @@ -39,7 +39,8 @@ async def sample_batch_annotate_images(): client = vision_v1p4beta1.ImageAnnotatorAsyncClient() # Initialize request argument(s) - request = vision_v1p4beta1.BatchAnnotateImagesRequest() + request = vision_v1p4beta1.BatchAnnotateImagesRequest( + ) # Make the request response = await client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ async def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_BatchAnnotateImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_sync.py index 8e46bd3fef74..441445dbe624 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_batch_annotate_images_sync.py @@ -39,7 +39,8 @@ def sample_batch_annotate_images(): client = vision_v1p4beta1.ImageAnnotatorClient() # Initialize request argument(s) - request = vision_v1p4beta1.BatchAnnotateImagesRequest() + request = vision_v1p4beta1.BatchAnnotateImagesRequest( + ) # Make the request response = client.batch_annotate_images(request=request) @@ -47,5 +48,4 @@ def sample_batch_annotate_images(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ImageAnnotator_BatchAnnotateImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_async.py index b24246920a34..fdfa7de99a04 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_async.py @@ -49,5 +49,4 @@ async def sample_create_product(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_CreateProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_async.py index e9dd5cd31f33..b22cbdf35bfe 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_async.py @@ -49,5 +49,4 @@ async def sample_create_product_set(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_CreateProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_sync.py index daa31e8c03d5..6ac99ef6899a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_set_sync.py @@ -49,5 +49,4 @@ def sample_create_product_set(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_CreateProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_sync.py index 57f672ba98ed..d9188e29914d 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_product_sync.py @@ -49,5 +49,4 @@ def sample_create_product(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_CreateProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_async.py index 300af2d100de..caf6a464b210 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_async.py @@ -53,5 +53,4 @@ async def sample_create_reference_image(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_CreateReferenceImage_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_sync.py index f7f8ccdbef0f..ad42aca10e78 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_create_reference_image_sync.py @@ -53,5 +53,4 @@ def sample_create_reference_image(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_CreateReferenceImage_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_async.py index 0ce2b320e4d2..4f1715c3cc47 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_async.py @@ -49,5 +49,4 @@ async def sample_get_product(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_GetProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_async.py index 020484624de2..b4ebb79f24fa 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_async.py @@ -49,5 +49,4 @@ async def sample_get_product_set(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_GetProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_sync.py index 0e78856cc59e..2f564173885a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_set_sync.py @@ -49,5 +49,4 @@ def sample_get_product_set(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_GetProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_sync.py index c1584428292c..290c3c1f0155 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_product_sync.py @@ -49,5 +49,4 @@ def sample_get_product(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_GetProduct_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_async.py index 11621f2ccf33..f5935a2bc952 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_async.py @@ -49,5 +49,4 @@ async def sample_get_reference_image(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_GetReferenceImage_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_sync.py index d8e180a86dac..85a2c25ee7c2 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_get_reference_image_sync.py @@ -49,5 +49,4 @@ def sample_get_reference_image(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_GetReferenceImage_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py index 4301c81b5a67..6f7c38959e2e 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py @@ -53,5 +53,4 @@ async def sample_import_product_sets(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ImportProductSets_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_sync.py index 642dbb853982..a29af665a278 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_sync.py @@ -53,5 +53,4 @@ def sample_import_product_sets(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ImportProductSets_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_async.py index 34182ade796a..1c650281b218 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_async.py @@ -50,5 +50,4 @@ async def sample_list_product_sets(): async for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListProductSets_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_sync.py index 272032cb6344..6b132c89723c 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_product_sets_sync.py @@ -50,5 +50,4 @@ def sample_list_product_sets(): for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListProductSets_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_async.py index ff8659205c6d..ddcf7dadee24 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_async.py @@ -50,5 +50,4 @@ async def sample_list_products(): async for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListProducts_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_async.py index 2e3afcdfb6c6..03237fa278af 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_async.py @@ -50,5 +50,4 @@ async def sample_list_products_in_product_set(): async for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListProductsInProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_sync.py index 87b4f830d02e..d0ec4cab57f3 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_in_product_set_sync.py @@ -50,5 +50,4 @@ def sample_list_products_in_product_set(): for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListProductsInProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_sync.py index 140c9049a9ec..8c61d3c3cc75 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_products_sync.py @@ -50,5 +50,4 @@ def sample_list_products(): for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListProducts_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_async.py index ee2319491ad3..5b79efe5d8e2 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_async.py @@ -50,5 +50,4 @@ async def sample_list_reference_images(): async for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListReferenceImages_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_sync.py index 3204df1efff3..56e82a10451c 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_list_reference_images_sync.py @@ -50,5 +50,4 @@ def sample_list_reference_images(): for response in page_result: print(response) - # [END vision_v1p4beta1_generated_ProductSearch_ListReferenceImages_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py index e9cddbb9b73a..d1f6a20f5cc3 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py @@ -53,5 +53,4 @@ async def sample_purge_products(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_PurgeProducts_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_sync.py index 245b41dd4549..e4839d4ff6ac 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_sync.py @@ -53,5 +53,4 @@ def sample_purge_products(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_PurgeProducts_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_async.py index 64bdca23ca03..4eab864c3bad 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_async.py @@ -39,7 +39,8 @@ async def sample_update_product(): client = vision_v1p4beta1.ProductSearchAsyncClient() # Initialize request argument(s) - request = vision_v1p4beta1.UpdateProductRequest() + request = vision_v1p4beta1.UpdateProductRequest( + ) # Make the request response = await client.update_product(request=request) @@ -47,5 +48,4 @@ async def sample_update_product(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_UpdateProduct_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_async.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_async.py index b5b95a923293..a23644a4ae2a 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_async.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_async.py @@ -39,7 +39,8 @@ async def sample_update_product_set(): client = vision_v1p4beta1.ProductSearchAsyncClient() # Initialize request argument(s) - request = vision_v1p4beta1.UpdateProductSetRequest() + request = vision_v1p4beta1.UpdateProductSetRequest( + ) # Make the request response = await client.update_product_set(request=request) @@ -47,5 +48,4 @@ async def sample_update_product_set(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_UpdateProductSet_async] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_sync.py index 56ba66eeaef6..12b3ac478cb6 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_set_sync.py @@ -39,7 +39,8 @@ def sample_update_product_set(): client = vision_v1p4beta1.ProductSearchClient() # Initialize request argument(s) - request = vision_v1p4beta1.UpdateProductSetRequest() + request = vision_v1p4beta1.UpdateProductSetRequest( + ) # Make the request response = client.update_product_set(request=request) @@ -47,5 +48,4 @@ def sample_update_product_set(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_UpdateProductSet_sync] diff --git a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_sync.py b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_sync.py index 60fd080ea28f..e9958f272eed 100644 --- a/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_sync.py +++ b/packages/google-cloud-vision/samples/generated_samples/vision_v1p4beta1_generated_product_search_update_product_sync.py @@ -39,7 +39,8 @@ def sample_update_product(): client = vision_v1p4beta1.ProductSearchClient() # Initialize request argument(s) - request = vision_v1p4beta1.UpdateProductRequest() + request = vision_v1p4beta1.UpdateProductRequest( + ) # Make the request response = client.update_product(request=request) @@ -47,5 +48,4 @@ def sample_update_product(): # Handle the response print(response) - # [END vision_v1p4beta1_generated_ProductSearch_UpdateProduct_sync] diff --git a/packages/google-cloud-vision/setup.py b/packages/google-cloud-vision/setup.py index 57f4070f9c7d..f025cecf091e 100644 --- a/packages/google-cloud-vision/setup.py +++ b/packages/google-cloud-vision/setup.py @@ -17,20 +17,20 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = "google-cloud-vision" +name = 'google-cloud-vision' description = "Google Cloud Vision API client library" version = None -with open(os.path.join(package_root, "google/cloud/vision/gapic_version.py")) as fp: +with open(os.path.join(package_root, 'google/cloud/vision/gapic_version.py')) as fp: version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert len(version_candidates) == 1 + assert (len(version_candidates) == 1) version = version_candidates[0] if version[0] == "0": @@ -49,7 +49,8 @@ "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] -extras = {} +extras = { +} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/google-cloud-vision/tests/__init__.py b/packages/google-cloud-vision/tests/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/__init__.py +++ b/packages/google-cloud-vision/tests/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/__init__.py b/packages/google-cloud-vision/tests/unit/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/__init__.py +++ b/packages/google-cloud-vision/tests/unit/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/__init__.py b/packages/google-cloud-vision/tests/unit/gapic/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1/__init__.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_image_annotator.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_image_annotator.py index 9c169e69edaf..209c0624519f 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_image_annotator.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_image_annotator.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,53 +21,52 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1.services.image_annotator import ImageAnnotatorAsyncClient +from google.cloud.vision_v1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1.services.image_annotator import transports +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import image_annotator +from google.cloud.vision_v1.types import product_search +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.type import latlng_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1.services.image_annotator import ( - ImageAnnotatorAsyncClient, - ImageAnnotatorClient, - transports, -) -from google.cloud.vision_v1.types import geometry, image_annotator, product_search CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -83,11 +81,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -95,27 +91,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -126,43 +112,20 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - True, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -176,46 +139,27 @@ def test__read_environment_variables(): ) else: assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ImageAnnotatorClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ImageAnnotatorClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ImageAnnotatorClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -224,9 +168,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ImageAnnotatorClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -234,9 +176,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -248,9 +188,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -262,9 +200,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -276,9 +212,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -293,167 +227,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ImageAnnotatorClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ImageAnnotatorClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ImageAnnotatorClient._get_client_cert_source(None, False) is None - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) - - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ImageAnnotatorClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ImageAnnotatorClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ImageAnnotatorClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ImageAnnotatorClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ImageAnnotatorClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ImageAnnotatorClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, None) - == ImageAnnotatorClient._DEFAULT_UNIVERSE - ) + assert ImageAnnotatorClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageAnnotatorClient._get_universe_domain(None, None) == ImageAnnotatorClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ImageAnnotatorClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -469,8 +319,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -483,20 +332,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -504,68 +347,52 @@ def test_image_annotator_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ImageAnnotatorGrpcTransport, "grpc"), - (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageAnnotatorGrpcTransport, "grpc"), + (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -581,45 +408,30 @@ def test_image_annotator_client_get_transport_class(): assert transport == transports.ImageAnnotatorGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) -def test_image_annotator_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) +def test_image_annotator_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -637,15 +449,13 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -657,7 +467,7 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -677,22 +487,17 @@ def test_image_annotator_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -701,82 +506,48 @@ def test_image_annotator_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_annotator_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_image_annotator_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -795,22 +566,12 @@ def test_image_annotator_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -831,22 +592,15 @@ def test_image_annotator_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -856,31 +610,19 @@ def test_image_annotator_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorAsyncClient)) def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -888,25 +630,18 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -943,24 +678,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -991,24 +725,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1024,28 +757,16 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1055,50 +776,27 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test_image_annotator_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1121,19 +819,11 @@ def test_image_annotator_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1141,40 +831,27 @@ def test_image_annotator_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1183,40 +860,24 @@ def test_image_annotator_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), - ], -) -def test_image_annotator_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), +]) +def test_image_annotator_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1225,14 +886,11 @@ def test_image_annotator_client_client_options_credentials_file( api_audience=None, ) - def test_image_annotator_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ImageAnnotatorClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1247,38 +905,23 @@ def test_image_annotator_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_image_annotator_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_annotator_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1306,9 +949,9 @@ def test_image_annotator_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1319,14 +962,11 @@ def test_image_annotator_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) -def test_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) +def test_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1338,10 +978,11 @@ def test_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateImagesResponse() + call.return_value = image_annotator.BatchAnnotateImagesResponse( + ) response = client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1359,31 +1000,28 @@ def test_batch_annotate_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = image_annotator.BatchAnnotateImagesRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == image_annotator.BatchAnnotateImagesRequest( - parent="parent_value", + parent='parent_value', ) - def test_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1398,19 +1036,12 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1423,11 +1054,8 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1441,17 +1069,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_images] = mock_rpc request = {} await client.batch_annotate_images(request) @@ -1465,12 +1088,8 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateImagesRequest, -): +async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1482,12 +1101,11 @@ async def test_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) response = await client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1512,18 +1130,14 @@ def test_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1531,11 +1145,7 @@ def test_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val @@ -1549,14 +1159,9 @@ def test_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1565,22 +1170,16 @@ async def test_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1588,14 +1187,9 @@ async def test_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1607,22 +1201,15 @@ async def test_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateFilesRequest, - dict, - ], -) -def test_batch_annotate_files(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateFilesRequest, + dict, +]) +def test_batch_annotate_files(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1634,10 +1221,11 @@ def test_batch_annotate_files(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateFilesResponse() + call.return_value = image_annotator.BatchAnnotateFilesResponse( + ) response = client.batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -1655,31 +1243,28 @@ def test_batch_annotate_files_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = image_annotator.BatchAnnotateFilesRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_files), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_files(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == image_annotator.BatchAnnotateFilesRequest( - parent="parent_value", + parent='parent_value', ) - def test_batch_annotate_files_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1694,18 +1279,12 @@ def test_batch_annotate_files_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_files in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_files] = mock_rpc request = {} client.batch_annotate_files(request) @@ -1718,11 +1297,8 @@ def test_batch_annotate_files_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_files_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1736,17 +1312,12 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_files - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_files in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_files - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_files] = mock_rpc request = {} await client.batch_annotate_files(request) @@ -1760,12 +1331,8 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_files_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateFilesRequest, -): +async def test_batch_annotate_files_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateFilesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1777,12 +1344,11 @@ async def test_batch_annotate_files_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateFilesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateFilesResponse( + )) response = await client.batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -1807,20 +1373,14 @@ def test_batch_annotate_files_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateFilesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_files( - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1828,13 +1388,7 @@ def test_batch_annotate_files_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val @@ -1848,16 +1402,9 @@ def test_batch_annotate_files_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_files( image_annotator.BatchAnnotateFilesRequest(), - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) - @pytest.mark.asyncio async def test_batch_annotate_files_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1866,24 +1413,16 @@ async def test_batch_annotate_files_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateFilesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateFilesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateFilesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_files( - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1891,16 +1430,9 @@ async def test_batch_annotate_files_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_files_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1912,24 +1444,15 @@ async def test_batch_annotate_files_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_files( image_annotator.BatchAnnotateFilesRequest(), - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateImagesRequest, - dict, - ], -) -def test_async_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateImagesRequest, + dict, +]) +def test_async_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1941,10 +1464,10 @@ def test_async_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.async_batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1962,31 +1485,28 @@ def test_async_batch_annotate_images_non_empty_request_with_auto_populated_field # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = image_annotator.AsyncBatchAnnotateImagesRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.async_batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.async_batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest( - parent="parent_value", + parent='parent_value', ) - def test_async_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2001,19 +1521,12 @@ def test_async_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_images] = mock_rpc request = {} client.async_batch_annotate_images(request) @@ -2031,11 +1544,8 @@ def test_async_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2049,17 +1559,12 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.async_batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.async_batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.async_batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.async_batch_annotate_images] = mock_rpc request = {} await client.async_batch_annotate_images(request) @@ -2078,12 +1583,8 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.AsyncBatchAnnotateImagesRequest, -): +async def test_async_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.AsyncBatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2095,11 +1596,11 @@ async def test_async_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.async_batch_annotate_images(request) @@ -2125,21 +1626,15 @@ def test_async_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.async_batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) # Establish that the underlying call was made with the expected @@ -2147,16 +1642,10 @@ def test_async_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val arg = args[0].output_config - mock_val = image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ) + mock_val = image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')) assert arg == mock_val @@ -2170,17 +1659,10 @@ def test_async_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.async_batch_annotate_images( image_annotator.AsyncBatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) - @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -2189,25 +1671,19 @@ async def test_async_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.async_batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) # Establish that the underlying call was made with the expected @@ -2215,19 +1691,12 @@ async def test_async_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val arg = args[0].output_config - mock_val = image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ) + mock_val = image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')) assert arg == mock_val - @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -2239,25 +1708,16 @@ async def test_async_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.async_batch_annotate_images( image_annotator.AsyncBatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) -def test_async_batch_annotate_files(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) +def test_async_batch_annotate_files(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2269,10 +1729,10 @@ def test_async_batch_annotate_files(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.async_batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -2290,31 +1750,28 @@ def test_async_batch_annotate_files_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = image_annotator.AsyncBatchAnnotateFilesRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.async_batch_annotate_files(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest( - parent="parent_value", + parent='parent_value', ) - def test_async_batch_annotate_files_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2329,19 +1786,12 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -2359,11 +1809,8 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2377,17 +1824,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.async_batch_annotate_files - in client._client._transport._wrapped_methods - ) + assert client._client._transport.async_batch_annotate_files in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.async_batch_annotate_files - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.async_batch_annotate_files] = mock_rpc request = {} await client.async_batch_annotate_files(request) @@ -2406,12 +1848,8 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2423,11 +1861,11 @@ async def test_async_batch_annotate_files_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.async_batch_annotate_files(request) @@ -2453,20 +1891,14 @@ def test_async_batch_annotate_files_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -2474,13 +1906,7 @@ def test_async_batch_annotate_files_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val @@ -2494,16 +1920,9 @@ def test_async_batch_annotate_files_flattened_error(): with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -2512,24 +1931,18 @@ async def test_async_batch_annotate_files_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -2537,16 +1950,9 @@ async def test_async_batch_annotate_files_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -2558,13 +1964,7 @@ async def test_async_batch_annotate_files_flattened_error_async(): with pytest.raises(ValueError): await client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -2582,19 +1982,12 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -2609,57 +2002,52 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_images_rest_required_fields( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_required_fields(request_type=image_annotator.BatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2669,24 +2057,24 @@ def test_batch_annotate_images_rest_required_fields( return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_images_rest_flattened(): @@ -2696,7 +2084,7 @@ def test_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() @@ -2705,11 +2093,7 @@ def test_batch_annotate_images_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) mock_args.update(sample_request) @@ -2719,7 +2103,7 @@ def test_batch_annotate_images_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2729,12 +2113,10 @@ def test_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/images:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1/images:annotate" % client.transport._host, args[1]) -def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2745,11 +2127,7 @@ def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) @@ -2767,18 +2145,12 @@ def test_batch_annotate_files_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_files in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_files] = mock_rpc request = {} client.batch_annotate_files(request) @@ -2793,57 +2165,52 @@ def test_batch_annotate_files_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_files_rest_required_fields( - request_type=image_annotator.BatchAnnotateFilesRequest, -): +def test_batch_annotate_files_rest_required_fields(request_type=image_annotator.BatchAnnotateFilesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateFilesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2853,24 +2220,24 @@ def test_batch_annotate_files_rest_required_fields( return_value = image_annotator.BatchAnnotateFilesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_files(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_files_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_files._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_files_rest_flattened(): @@ -2880,7 +2247,7 @@ def test_batch_annotate_files_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateFilesResponse() @@ -2889,13 +2256,7 @@ def test_batch_annotate_files_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) mock_args.update(sample_request) @@ -2905,7 +2266,7 @@ def test_batch_annotate_files_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateFilesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2915,12 +2276,10 @@ def test_batch_annotate_files_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/files:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1/files:annotate" % client.transport._host, args[1]) -def test_batch_annotate_files_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_files_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2931,13 +2290,7 @@ def test_batch_annotate_files_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_files( image_annotator.BatchAnnotateFilesRequest(), - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -2955,19 +2308,12 @@ def test_async_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_images] = mock_rpc request = {} client.async_batch_annotate_images(request) @@ -2986,89 +2332,76 @@ def test_async_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_async_batch_annotate_images_rest_required_fields( - request_type=image_annotator.AsyncBatchAnnotateImagesRequest, -): +def test_async_batch_annotate_images_rest_required_fields(request_type=image_annotator.AsyncBatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_async_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.async_batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "requests", - "outputConfig", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("requests", "outputConfig", ))) def test_async_batch_annotate_images_rest_flattened(): @@ -3078,23 +2411,17 @@ def test_async_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method sample_request = {} # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) mock_args.update(sample_request) @@ -3102,7 +2429,7 @@ def test_async_batch_annotate_images_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3112,12 +2439,10 @@ def test_async_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/images:asyncBatchAnnotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1/images:asyncBatchAnnotate" % client.transport._host, args[1]) -def test_async_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_async_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3128,14 +2453,8 @@ def test_async_batch_annotate_images_rest_flattened_error(transport: str = "rest with pytest.raises(ValueError): client.async_batch_annotate_images( image_annotator.AsyncBatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) @@ -3153,19 +2472,12 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -3184,81 +2496,76 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_async_batch_annotate_files_rest_required_fields( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_required_fields(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_async_batch_annotate_files_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.async_batch_annotate_files._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_async_batch_annotate_files_rest_flattened(): @@ -3268,22 +2575,16 @@ def test_async_batch_annotate_files_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method sample_request = {} # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) mock_args.update(sample_request) @@ -3291,7 +2592,7 @@ def test_async_batch_annotate_files_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3301,12 +2602,10 @@ def test_async_batch_annotate_files_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/files:asyncBatchAnnotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1/files:asyncBatchAnnotate" % client.transport._host, args[1]) -def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest"): +def test_async_batch_annotate_files_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3317,13 +2616,7 @@ def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -3365,7 +2658,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ImageAnnotatorClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -3387,7 +2681,6 @@ def test_transport_instance(): client = ImageAnnotatorClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( @@ -3402,23 +2695,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - transports.ImageAnnotatorRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + transports.ImageAnnotatorRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ImageAnnotatorClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3428,7 +2716,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -3443,8 +2732,8 @@ def test_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateImagesResponse() client.batch_annotate_images(request=None) @@ -3466,8 +2755,8 @@ def test_batch_annotate_files_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateFilesResponse() client.batch_annotate_files(request=None) @@ -3489,9 +2778,9 @@ def test_async_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.async_batch_annotate_images), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.async_batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -3512,9 +2801,9 @@ def test_async_batch_annotate_files_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -3534,7 +2823,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -3550,12 +2840,11 @@ async def test_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) await client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -3577,12 +2866,11 @@ async def test_batch_annotate_files_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateFilesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateFilesResponse( + )) await client.batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -3604,11 +2892,11 @@ async def test_async_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.async_batch_annotate_images(request=None) @@ -3631,11 +2919,11 @@ async def test_async_batch_annotate_files_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.async_batch_annotate_files(request=None) @@ -3654,23 +2942,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_batch_annotate_images_rest_bad_request( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3679,16 +2964,14 @@ def test_batch_annotate_images_rest_bad_request( client.batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) def test_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -3696,9 +2979,10 @@ def test_batch_annotate_images_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateImagesResponse() + return_value = image_annotator.BatchAnnotateImagesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -3707,7 +2991,7 @@ def test_batch_annotate_images_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) @@ -3720,30 +3004,19 @@ def test_batch_annotate_images_rest_call_success(request_type): def test_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateImagesRequest.pb( - image_annotator.BatchAnnotateImagesRequest() - ) + pb_message = image_annotator.BatchAnnotateImagesRequest.pb(image_annotator.BatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3754,53 +3027,39 @@ def test_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateImagesResponse.to_json( - image_annotator.BatchAnnotateImagesResponse() - ) + return_value = image_annotator.BatchAnnotateImagesResponse.to_json(image_annotator.BatchAnnotateImagesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateImagesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateImagesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateImagesResponse(), metadata - client.batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_batch_annotate_files_rest_bad_request( - request_type=image_annotator.BatchAnnotateFilesRequest, -): +def test_batch_annotate_files_rest_bad_request(request_type=image_annotator.BatchAnnotateFilesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3809,16 +3068,14 @@ def test_batch_annotate_files_rest_bad_request( client.batch_annotate_files(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateFilesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateFilesRequest, + dict, +]) def test_batch_annotate_files_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -3826,9 +3083,10 @@ def test_batch_annotate_files_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateFilesResponse() + return_value = image_annotator.BatchAnnotateFilesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -3837,7 +3095,7 @@ def test_batch_annotate_files_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateFilesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_files(request) @@ -3850,30 +3108,19 @@ def test_batch_annotate_files_rest_call_success(request_type): def test_batch_annotate_files_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_files" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_files_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_files" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_files") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_files_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_files") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateFilesRequest.pb( - image_annotator.BatchAnnotateFilesRequest() - ) + pb_message = image_annotator.BatchAnnotateFilesRequest.pb(image_annotator.BatchAnnotateFilesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3884,53 +3131,39 @@ def test_batch_annotate_files_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateFilesResponse.to_json( - image_annotator.BatchAnnotateFilesResponse() - ) + return_value = image_annotator.BatchAnnotateFilesResponse.to_json(image_annotator.BatchAnnotateFilesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateFilesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateFilesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateFilesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateFilesResponse(), metadata - client.batch_annotate_files( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_files(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_async_batch_annotate_images_rest_bad_request( - request_type=image_annotator.AsyncBatchAnnotateImagesRequest, -): +def test_async_batch_annotate_images_rest_bad_request(request_type=image_annotator.AsyncBatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3939,16 +3172,14 @@ def test_async_batch_annotate_images_rest_bad_request( client.async_batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateImagesRequest, + dict, +]) def test_async_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -3956,15 +3187,15 @@ def test_async_batch_annotate_images_rest_call_success(request_type): 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_images(request) @@ -3977,32 +3208,20 @@ def test_async_batch_annotate_images_rest_call_success(request_type): def test_async_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_async_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_images" - ) as pre: + 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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.AsyncBatchAnnotateImagesRequest.pb( - image_annotator.AsyncBatchAnnotateImagesRequest() - ) + pb_message = image_annotator.AsyncBatchAnnotateImagesRequest.pb(image_annotator.AsyncBatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4017,7 +3236,7 @@ def test_async_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value.content = return_value request = image_annotator.AsyncBatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4025,36 +3244,27 @@ def test_async_batch_annotate_images_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.async_batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.async_batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_async_batch_annotate_files_rest_bad_request( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4063,16 +3273,14 @@ def test_async_batch_annotate_files_rest_bad_request( client.async_batch_annotate_files(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) def test_async_batch_annotate_files_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -4080,15 +3288,15 @@ def test_async_batch_annotate_files_rest_call_success(request_type): 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) @@ -4101,32 +3309,20 @@ def test_async_batch_annotate_files_rest_call_success(request_type): def test_async_batch_annotate_files_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_async_batch_annotate_files_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files" - ) as pre: + 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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb( - image_annotator.AsyncBatchAnnotateFilesRequest() - ) + pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb(image_annotator.AsyncBatchAnnotateFilesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4141,7 +3337,7 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): req.return_value.content = return_value request = image_annotator.AsyncBatchAnnotateFilesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4149,38 +3345,26 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.async_batch_annotate_files( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.async_batch_annotate_files(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_operation_rest_bad_request( - request_type=operations_pb2.GetOperationRequest, -): +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/operations/sample2"}, request - ) + request = json_format.ParseDict({'name': 'projects/sample1/operations/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -4189,23 +3373,20 @@ def test_get_operation_rest_bad_request( client.get_operation(request) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) def test_get_operation_rest(request_type): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/operations/sample2"} + request_init = {'name': 'projects/sample1/operations/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + with mock.patch.object(Session, 'request') as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation() @@ -4213,7 +3394,7 @@ def test_get_operation_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4223,10 +3404,10 @@ def test_get_operation_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) - def test_initialize_client_w_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -4241,8 +3422,8 @@ def test_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -4263,8 +3444,8 @@ def test_batch_annotate_files_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: client.batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -4285,8 +3466,8 @@ def test_async_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: client.async_batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -4307,8 +3488,8 @@ def test_async_batch_annotate_files_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -4329,13 +3510,12 @@ def test_image_annotator_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ImageAnnotatorClient( @@ -4346,21 +3526,18 @@ def test_transport_grpc_default(): transports.ImageAnnotatorGrpcTransport, ) - def test_image_annotator_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_image_annotator_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport.__init__') as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4369,11 +3546,11 @@ def test_image_annotator_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "batch_annotate_images", - "batch_annotate_files", - "async_batch_annotate_images", - "async_batch_annotate_files", - "get_operation", + 'batch_annotate_images', + 'batch_annotate_files', + 'async_batch_annotate_images', + 'async_batch_annotate_files', + 'get_operation', ) for method in methods: with pytest.raises(NotImplementedError): @@ -4389,7 +3566,7 @@ def test_image_annotator_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4398,33 +3575,26 @@ def test_image_annotator_base_transport(): def test_image_annotator_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.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_image_annotator_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.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() @@ -4433,15 +3603,15 @@ def test_image_annotator_base_transport_with_adc(): def test_image_annotator_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -4456,15 +3626,12 @@ def test_image_annotator_auth_adc(): def test_image_annotator_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -4478,38 +3645,39 @@ def test_image_annotator_transport_auth_adc(transport_class): ], ) def test_image_annotator_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ImageAnnotatorGrpcTransport, grpc_helpers), - (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_image_annotator_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -4517,9 +3685,9 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -4530,14 +3698,10 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4546,7 +3710,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -4567,77 +3731,61 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_image_annotator_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.ImageAnnotatorRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ImageAnnotatorRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_no_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_with_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_image_annotator_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4661,10 +3809,8 @@ def test_image_annotator_client_transport_session_collision(transport_name): session1 = client1.transport.async_batch_annotate_files._session session2 = client2.transport.async_batch_annotate_files._session assert session1 != session2 - - def test_image_annotator_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcTransport( @@ -4677,7 +3823,7 @@ def test_image_annotator_grpc_transport_channel(): def test_image_annotator_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcAsyncIOTransport( @@ -4692,22 +3838,12 @@ def test_image_annotator_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) def test_image_annotator_transport_channel_mtls_with_client_cert_source( - transport_class, + 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: + 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 @@ -4716,7 +3852,7 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -4746,23 +3882,17 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( # 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.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_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: + 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() @@ -4793,7 +3923,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -4810,7 +3940,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -4828,11 +3958,7 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + expected = "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) actual = ImageAnnotatorClient.product_path(project, location, product) assert expected == actual @@ -4849,18 +3975,11 @@ def test_parse_product_path(): actual = ImageAnnotatorClient.parse_product_path(path) assert expected == actual - def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) actual = ImageAnnotatorClient.product_set_path(project, location, product_set) assert expected == actual @@ -4877,12 +3996,9 @@ def test_parse_product_set_path(): actual = ImageAnnotatorClient.parse_product_set_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ImageAnnotatorClient.common_billing_account_path(billing_account) assert expected == actual @@ -4897,12 +4013,9 @@ def test_parse_common_billing_account_path(): actual = ImageAnnotatorClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -4917,12 +4030,9 @@ def test_parse_common_folder_path(): actual = ImageAnnotatorClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -4937,12 +4047,9 @@ def test_parse_common_organization_path(): actual = ImageAnnotatorClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -4957,14 +4064,10 @@ def test_parse_common_project_path(): actual = ImageAnnotatorClient.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, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ImageAnnotatorClient.common_location_path(project, location) assert expected == actual @@ -4984,18 +4087,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5006,8 +4105,7 @@ def test_client_with_default_client_info(): def test_get_operation(transport: str = "grpc"): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5026,13 +4124,10 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) - - @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, + credentials=async_anonymous_credentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5054,7 +4149,6 @@ async def test_get_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) - def test_get_operation_field_headers(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5077,12 +4171,7 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=locations", - ) in kw["metadata"] - - + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ImageAnnotatorAsyncClient( @@ -5107,11 +4196,7 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=locations", - ) in kw["metadata"] - + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] def test_get_operation_from_dict(): client = ImageAnnotatorClient( @@ -5128,8 +4213,6 @@ def test_get_operation_from_dict(): } ) call.assert_called() - - @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ImageAnnotatorAsyncClient( @@ -5151,11 +4234,10 @@ async def test_get_operation_from_dict_async(): def test_transport_close_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -5164,11 +4246,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -5176,11 +4257,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -5188,12 +4268,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -5202,14 +4283,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), - (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5224,9 +4301,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_product_search.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_product_search.py index c7be6a7ce441..a0413eb168ed 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_product_search.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1/test_product_search.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,58 +21,56 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1.services.product_search import ProductSearchAsyncClient +from google.cloud.vision_v1.services.product_search import ProductSearchClient +from google.cloud.vision_v1.services.product_search import pagers +from google.cloud.vision_v1.services.product_search import transports +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1.services.product_search import ( - ProductSearchAsyncClient, - ProductSearchClient, - pagers, - transports, -) -from google.cloud.vision_v1.types import geometry, product_search_service CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -88,11 +85,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -100,27 +95,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -131,26 +116,11 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ProductSearchClient._get_default_mtls_endpoint(None) is None - assert ( - ProductSearchClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ProductSearchClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ProductSearchClient._read_environment_variables() == (False, "auto", None) @@ -159,11 +129,7 @@ def test__read_environment_variables(): assert ProductSearchClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -177,46 +143,27 @@ def test__read_environment_variables(): ) else: assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ProductSearchClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ProductSearchClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ProductSearchClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -225,9 +172,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ProductSearchClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -235,9 +180,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ProductSearchClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -249,9 +192,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -263,9 +204,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -277,9 +216,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -294,167 +231,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ProductSearchClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ProductSearchClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ProductSearchClient._get_client_cert_source(None, False) is None - assert ( - ProductSearchClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ProductSearchClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) - - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ProductSearchClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ProductSearchClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ProductSearchClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ProductSearchClient._DEFAULT_UNIVERSE - default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ProductSearchClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "always") - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ProductSearchClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "always") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ProductSearchClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ProductSearchClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ProductSearchClient._get_universe_domain(None, None) - == ProductSearchClient._DEFAULT_UNIVERSE - ) + assert ProductSearchClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProductSearchClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProductSearchClient._get_universe_domain(None, None) == ProductSearchClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ProductSearchClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -470,8 +323,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -484,20 +336,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ProductSearchClient, "grpc"), - (ProductSearchAsyncClient, "grpc_asyncio"), - (ProductSearchClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductSearchClient, "grpc"), + (ProductSearchAsyncClient, "grpc_asyncio"), + (ProductSearchClient, "rest"), +]) def test_product_search_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -505,68 +351,52 @@ def test_product_search_client_from_service_account_info(client_class, transport assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ProductSearchGrpcTransport, "grpc"), - (transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProductSearchRestTransport, "rest"), - ], -) -def test_product_search_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductSearchGrpcTransport, "grpc"), + (transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProductSearchRestTransport, "rest"), +]) +def test_product_search_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ProductSearchClient, "grpc"), - (ProductSearchAsyncClient, "grpc_asyncio"), - (ProductSearchClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductSearchClient, "grpc"), + (ProductSearchAsyncClient, "grpc_asyncio"), + (ProductSearchClient, "rest"), +]) def test_product_search_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -582,45 +412,30 @@ def test_product_search_client_get_transport_class(): assert transport == transports.ProductSearchGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), - ], -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) -def test_product_search_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) +def test_product_search_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ProductSearchClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + with mock.patch.object(ProductSearchClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -638,15 +453,13 @@ def test_product_search_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -658,7 +471,7 @@ def test_product_search_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -678,22 +491,17 @@ def test_product_search_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -702,82 +510,48 @@ def test_product_search_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "true"), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "true"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "false"), +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_search_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_product_search_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -796,22 +570,12 @@ def test_product_search_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -832,22 +596,15 @@ def test_product_search_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -857,31 +614,19 @@ def test_product_search_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ProductSearchClient, ProductSearchAsyncClient] -) -@mock.patch.object( - ProductSearchClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ProductSearchAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ProductSearchClient, ProductSearchAsyncClient +]) +@mock.patch.object(ProductSearchClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductSearchAsyncClient)) def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -889,25 +634,18 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -944,24 +682,23 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -992,24 +729,23 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1025,28 +761,16 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1056,50 +780,27 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ProductSearchClient, ProductSearchAsyncClient] -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ProductSearchClient, ProductSearchAsyncClient +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) def test_product_search_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ProductSearchClient._DEFAULT_UNIVERSE - default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1122,19 +823,11 @@ def test_product_search_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1142,40 +835,27 @@ def test_product_search_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), - ], -) -def test_product_search_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), +]) +def test_product_search_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1184,40 +864,24 @@ def test_product_search_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ProductSearchClient, - transports.ProductSearchGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", None), - ], -) -def test_product_search_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", grpc_helpers), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", None), +]) +def test_product_search_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1226,14 +890,11 @@ def test_product_search_client_client_options_credentials_file( api_audience=None, ) - def test_product_search_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1.services.product_search.transports.ProductSearchGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1.services.product_search.transports.ProductSearchGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ProductSearchClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1248,38 +909,23 @@ def test_product_search_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ProductSearchClient, - transports.ProductSearchGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_product_search_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", grpc_helpers), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_search_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1307,9 +953,9 @@ def test_product_search_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1320,14 +966,11 @@ def test_product_search_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductSetRequest, - dict, - ], -) -def test_create_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductSetRequest, + dict, +]) +def test_create_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1339,12 +982,12 @@ def test_create_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.create_product_set(request) @@ -1356,8 +999,8 @@ def test_create_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_create_product_set_non_empty_request_with_auto_populated_field(): @@ -1365,33 +1008,30 @@ def test_create_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateProductSetRequest( - parent="parent_value", - product_set_id="product_set_id_value", + parent='parent_value', + product_set_id='product_set_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.create_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateProductSetRequest( - parent="parent_value", - product_set_id="product_set_id_value", + parent='parent_value', + product_set_id='product_set_id_value', ) - def test_create_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1406,18 +1046,12 @@ def test_create_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_product_set in client._transport._wrapped_methods - ) + assert client._transport.create_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_product_set] = mock_rpc request = {} client.create_product_set(request) @@ -1430,11 +1064,8 @@ def test_create_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1448,17 +1079,12 @@ async def test_create_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_product_set] = mock_rpc request = {} await client.create_product_set(request) @@ -1472,12 +1098,8 @@ async def test_create_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateProductSetRequest, -): +async def test_create_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1489,15 +1111,13 @@ async def test_create_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.create_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -1508,15 +1128,14 @@ async def test_create_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_create_product_set_async_from_dict(): await test_create_product_set_async(request_type=dict) - def test_create_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1526,12 +1145,12 @@ def test_create_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductSetRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.create_product_set(request) @@ -1543,9 +1162,9 @@ def test_create_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1558,15 +1177,13 @@ async def test_create_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductSetRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + type(client.transport.create_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.create_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -1577,9 +1194,9 @@ async def test_create_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_product_set_flattened(): @@ -1589,16 +1206,16 @@ def test_create_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_product_set( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) # Establish that the underlying call was made with the expected @@ -1606,13 +1223,13 @@ def test_create_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].product_set_id - mock_val = "product_set_id_value" + mock_val = 'product_set_id_value' assert arg == mock_val @@ -1626,12 +1243,11 @@ def test_create_product_set_flattened_error(): with pytest.raises(ValueError): client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) - @pytest.mark.asyncio async def test_create_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -1640,20 +1256,18 @@ async def test_create_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_product_set( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) # Establish that the underlying call was made with the expected @@ -1661,16 +1275,15 @@ async def test_create_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].product_set_id - mock_val = "product_set_id_value" + mock_val = 'product_set_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -1682,20 +1295,17 @@ async def test_create_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductSetsRequest, - dict, - ], -) -def test_list_product_sets(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductSetsRequest, + dict, +]) +def test_list_product_sets(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1707,11 +1317,11 @@ def test_list_product_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_product_sets(request) @@ -1723,7 +1333,7 @@ def test_list_product_sets(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_product_sets_non_empty_request_with_auto_populated_field(): @@ -1731,33 +1341,30 @@ def test_list_product_sets_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductSetsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_product_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_product_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductSetsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_product_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1776,12 +1383,8 @@ def test_list_product_sets_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_product_sets] = mock_rpc request = {} client.list_product_sets(request) @@ -1794,11 +1397,8 @@ def test_list_product_sets_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_product_sets_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1812,17 +1412,12 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_product_sets - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_product_sets in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_product_sets - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_product_sets] = mock_rpc request = {} await client.list_product_sets(request) @@ -1836,12 +1431,8 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_product_sets_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductSetsRequest, -): +async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductSetsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1853,14 +1444,12 @@ async def test_list_product_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse( + next_page_token='next_page_token_value', + )) response = await client.list_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -1871,14 +1460,13 @@ async def test_list_product_sets_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_product_sets_async_from_dict(): await test_list_product_sets_async(request_type=dict) - def test_list_product_sets_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1888,12 +1476,12 @@ def test_list_product_sets_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: call.return_value = product_search_service.ListProductSetsResponse() client.list_product_sets(request) @@ -1905,9 +1493,9 @@ def test_list_product_sets_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1920,15 +1508,13 @@ async def test_list_product_sets_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse() - ) + type(client.transport.list_product_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse()) await client.list_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -1939,9 +1525,9 @@ async def test_list_product_sets_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_product_sets_flattened(): @@ -1951,14 +1537,14 @@ def test_list_product_sets_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_product_sets( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -1966,7 +1552,7 @@ def test_list_product_sets_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -1980,10 +1566,9 @@ def test_list_product_sets_flattened_error(): with pytest.raises(ValueError): client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_product_sets_flattened_async(): client = ProductSearchAsyncClient( @@ -1992,18 +1577,16 @@ async def test_list_product_sets_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_product_sets( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -2011,10 +1594,9 @@ async def test_list_product_sets_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_product_sets_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2026,7 +1608,7 @@ async def test_list_product_sets_flattened_error_async(): with pytest.raises(ValueError): await client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -2038,8 +1620,8 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2048,17 +1630,17 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2073,7 +1655,9 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_product_sets(request={}, retry=retry, timeout=timeout) @@ -2083,9 +1667,8 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in results) - - + assert all(isinstance(i, product_search_service.ProductSet) + for i in results) def test_list_product_sets_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2094,8 +1677,8 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2104,17 +1687,17 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2125,10 +1708,9 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_product_sets(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_product_sets_async_pager(): client = ProductSearchAsyncClient( @@ -2137,10 +1719,8 @@ async def test_list_product_sets_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_product_sets), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2149,17 +1729,17 @@ async def test_list_product_sets_async_pager(): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2169,16 +1749,15 @@ async def test_list_product_sets_async_pager(): ), RuntimeError, ) - async_pager = await client.list_product_sets( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_product_sets(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in responses) + assert all(isinstance(i, product_search_service.ProductSet) + for i in responses) @pytest.mark.asyncio @@ -2189,10 +1768,8 @@ async def test_list_product_sets_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_product_sets), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2201,17 +1778,17 @@ async def test_list_product_sets_async_pages(): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2224,22 +1801,18 @@ async def test_list_product_sets_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_product_sets(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductSetRequest, - dict, - ], -) -def test_get_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductSetRequest, + dict, +]) +def test_get_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2250,11 +1823,13 @@ def test_get_product_set(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.get_product_set(request) @@ -2266,8 +1841,8 @@ def test_get_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_get_product_set_non_empty_request_with_auto_populated_field(): @@ -2275,29 +1850,28 @@ def test_get_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetProductSetRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetProductSetRequest( - name="name_value", + name='name_value', ) - def test_get_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2316,9 +1890,7 @@ def test_get_product_set_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product_set] = mock_rpc request = {} client.get_product_set(request) @@ -2332,11 +1904,8 @@ def test_get_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2350,17 +1919,12 @@ async def test_get_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_product_set] = mock_rpc request = {} await client.get_product_set(request) @@ -2374,12 +1938,8 @@ async def test_get_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetProductSetRequest, -): +async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2390,14 +1950,14 @@ async def test_get_product_set_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.get_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2408,15 +1968,14 @@ async def test_get_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_get_product_set_async_from_dict(): await test_get_product_set_async(request_type=dict) - def test_get_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2426,10 +1985,12 @@ def test_get_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.get_product_set(request) @@ -2441,9 +2002,9 @@ def test_get_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2456,13 +2017,13 @@ async def test_get_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.get_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2473,9 +2034,9 @@ async def test_get_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_product_set_flattened(): @@ -2484,13 +2045,15 @@ def test_get_product_set_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -2498,7 +2061,7 @@ def test_get_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -2512,10 +2075,9 @@ def test_get_product_set_flattened_error(): with pytest.raises(ValueError): client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -2523,17 +2085,17 @@ async def test_get_product_set_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -2541,10 +2103,9 @@ async def test_get_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2556,18 +2117,15 @@ async def test_get_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductSetRequest, - dict, - ], -) -def test_update_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductSetRequest, + dict, +]) +def test_update_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2579,12 +2137,12 @@ def test_update_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.update_product_set(request) @@ -2596,8 +2154,8 @@ def test_update_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_update_product_set_non_empty_request_with_auto_populated_field(): @@ -2605,26 +2163,25 @@ def test_update_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = product_search_service.UpdateProductSetRequest() + request = product_search_service.UpdateProductSetRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.update_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.update_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductSetRequest() - + assert args[0] == product_search_service.UpdateProductSetRequest( + ) def test_update_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2640,18 +2197,12 @@ def test_update_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_product_set in client._transport._wrapped_methods - ) + assert client._transport.update_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_product_set] = mock_rpc request = {} client.update_product_set(request) @@ -2664,11 +2215,8 @@ def test_update_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2682,17 +2230,12 @@ async def test_update_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.update_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.update_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.update_product_set] = mock_rpc request = {} await client.update_product_set(request) @@ -2706,12 +2249,8 @@ async def test_update_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.UpdateProductSetRequest, -): +async def test_update_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.UpdateProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2723,15 +2262,13 @@ async def test_update_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.update_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2742,15 +2279,14 @@ async def test_update_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_update_product_set_async_from_dict(): await test_update_product_set_async(request_type=dict) - def test_update_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2760,12 +2296,12 @@ def test_update_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductSetRequest() - request.product_set.name = "name_value" + request.product_set.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.update_product_set(request) @@ -2777,9 +2313,9 @@ def test_update_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product_set.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product_set.name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2792,15 +2328,13 @@ async def test_update_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductSetRequest() - request.product_set.name = "name_value" + request.product_set.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + type(client.transport.update_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.update_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2811,9 +2345,9 @@ async def test_update_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product_set.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product_set.name=name_value', + ) in kw['metadata'] def test_update_product_set_flattened(): @@ -2823,15 +2357,15 @@ def test_update_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_product_set( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -2839,10 +2373,10 @@ def test_update_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val @@ -2856,11 +2390,10 @@ def test_update_product_set_flattened_error(): with pytest.raises(ValueError): client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) - @pytest.mark.asyncio async def test_update_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -2869,19 +2402,17 @@ async def test_update_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_product_set( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -2889,13 +2420,12 @@ async def test_update_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val - @pytest.mark.asyncio async def test_update_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2907,19 +2437,16 @@ async def test_update_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductSetRequest, - dict, - ], -) -def test_delete_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductSetRequest, + dict, +]) +def test_delete_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2931,8 +2458,8 @@ def test_delete_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_product_set(request) @@ -2952,31 +2479,28 @@ def test_delete_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteProductSetRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.delete_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteProductSetRequest( - name="name_value", + name='name_value', ) - def test_delete_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2991,18 +2515,12 @@ def test_delete_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_product_set in client._transport._wrapped_methods - ) + assert client._transport.delete_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_set] = mock_rpc request = {} client.delete_product_set(request) @@ -3015,11 +2533,8 @@ def test_delete_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3033,17 +2548,12 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_product_set] = mock_rpc request = {} await client.delete_product_set(request) @@ -3057,12 +2567,8 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteProductSetRequest, -): +async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3074,8 +2580,8 @@ async def test_delete_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_product_set(request) @@ -3094,7 +2600,6 @@ async def test_delete_product_set_async( async def test_delete_product_set_async_from_dict(): await test_delete_product_set_async(request_type=dict) - def test_delete_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3104,12 +2609,12 @@ def test_delete_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = None client.delete_product_set(request) @@ -3121,9 +2626,9 @@ def test_delete_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3136,12 +2641,12 @@ async def test_delete_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product_set(request) @@ -3153,9 +2658,9 @@ async def test_delete_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_product_set_flattened(): @@ -3165,14 +2670,14 @@ def test_delete_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -3180,7 +2685,7 @@ def test_delete_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -3194,10 +2699,9 @@ def test_delete_product_set_flattened_error(): with pytest.raises(ValueError): client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -3206,8 +2710,8 @@ async def test_delete_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3215,7 +2719,7 @@ async def test_delete_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -3223,10 +2727,9 @@ async def test_delete_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3238,18 +2741,15 @@ async def test_delete_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductRequest, - dict, - ], -) -def test_create_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3260,13 +2760,15 @@ def test_create_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.create_product(request) @@ -3278,10 +2780,10 @@ def test_create_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_create_product_non_empty_request_with_auto_populated_field(): @@ -3289,31 +2791,30 @@ def test_create_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateProductRequest( - parent="parent_value", - product_id="product_id_value", + parent='parent_value', + product_id='product_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateProductRequest( - parent="parent_value", - product_id="product_id_value", + parent='parent_value', + product_id='product_id_value', ) - def test_create_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3332,9 +2833,7 @@ def test_create_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.create_product] = mock_rpc request = {} client.create_product(request) @@ -3348,11 +2847,8 @@ def test_create_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3366,17 +2862,12 @@ async def test_create_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_product] = mock_rpc request = {} await client.create_product(request) @@ -3390,12 +2881,8 @@ async def test_create_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateProductRequest, -): +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3406,16 +2893,16 @@ async def test_create_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.create_product(request) # Establish that the underlying gRPC stub method was called. @@ -3426,17 +2913,16 @@ async def test_create_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_create_product_async_from_dict(): await test_create_product_async(request_type=dict) - def test_create_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3446,10 +2932,12 @@ def test_create_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: call.return_value = product_search_service.Product() client.create_product(request) @@ -3461,9 +2949,9 @@ def test_create_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3476,13 +2964,13 @@ async def test_create_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.create_product(request) # Establish that the underlying gRPC stub method was called. @@ -3493,9 +2981,9 @@ async def test_create_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_product_flattened(): @@ -3504,15 +2992,17 @@ def test_create_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_product( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) # Establish that the underlying call was made with the expected @@ -3520,13 +3010,13 @@ def test_create_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].product_id - mock_val = "product_id_value" + mock_val = 'product_id_value' assert arg == mock_val @@ -3540,12 +3030,11 @@ def test_create_product_flattened_error(): with pytest.raises(ValueError): client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) - @pytest.mark.asyncio async def test_create_product_flattened_async(): client = ProductSearchAsyncClient( @@ -3553,19 +3042,19 @@ async def test_create_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_product( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) # Establish that the underlying call was made with the expected @@ -3573,16 +3062,15 @@ async def test_create_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].product_id - mock_val = "product_id_value" + mock_val = 'product_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3594,20 +3082,17 @@ async def test_create_product_flattened_error_async(): with pytest.raises(ValueError): await client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsRequest, - dict, - ], -) -def test_list_products(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3618,10 +3103,12 @@ def test_list_products(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_products(request) @@ -3633,7 +3120,7 @@ def test_list_products(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_products_non_empty_request_with_auto_populated_field(): @@ -3641,31 +3128,30 @@ def test_list_products_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_products(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_products_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3684,9 +3170,7 @@ def test_list_products_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} client.list_products(request) @@ -3700,11 +3184,8 @@ def test_list_products_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3718,17 +3199,12 @@ async def test_list_products_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_products - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_products in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_products - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_products] = mock_rpc request = {} await client.list_products(request) @@ -3742,12 +3218,8 @@ async def test_list_products_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductsRequest, -): +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3758,13 +3230,13 @@ async def test_list_products_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) response = await client.list_products(request) # Establish that the underlying gRPC stub method was called. @@ -3775,14 +3247,13 @@ async def test_list_products_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_products_async_from_dict(): await test_list_products_async(request_type=dict) - def test_list_products_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3792,10 +3263,12 @@ def test_list_products_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: call.return_value = product_search_service.ListProductsResponse() client.list_products(request) @@ -3807,9 +3280,9 @@ def test_list_products_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3822,13 +3295,13 @@ async def test_list_products_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse() - ) + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse()) await client.list_products(request) # Establish that the underlying gRPC stub method was called. @@ -3839,9 +3312,9 @@ async def test_list_products_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_products_flattened(): @@ -3850,13 +3323,15 @@ def test_list_products_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -3864,7 +3339,7 @@ def test_list_products_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -3878,10 +3353,9 @@ def test_list_products_flattened_error(): with pytest.raises(ValueError): client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_products_flattened_async(): client = ProductSearchAsyncClient( @@ -3889,17 +3363,17 @@ async def test_list_products_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -3907,10 +3381,9 @@ async def test_list_products_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_products_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3922,7 +3395,7 @@ async def test_list_products_flattened_error_async(): with pytest.raises(ValueError): await client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -3933,7 +3406,9 @@ def test_list_products_pager(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -3942,17 +3417,17 @@ def test_list_products_pager(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -3967,7 +3442,9 @@ def test_list_products_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_products(request={}, retry=retry, timeout=timeout) @@ -3977,9 +3454,8 @@ def test_list_products_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) - - + assert all(isinstance(i, product_search_service.Product) + for i in results) def test_list_products_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3987,7 +3463,9 @@ def test_list_products_pages(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -3996,17 +3474,17 @@ def test_list_products_pages(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4017,10 +3495,9 @@ def test_list_products_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_products(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_products_async_pager(): client = ProductSearchAsyncClient( @@ -4029,8 +3506,8 @@ async def test_list_products_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products), "__call__", new_callable=mock.AsyncMock - ) as call: + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -4039,17 +3516,17 @@ async def test_list_products_async_pager(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4059,16 +3536,15 @@ async def test_list_products_async_pager(): ), RuntimeError, ) - async_pager = await client.list_products( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_products(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.Product) for i in responses) + assert all(isinstance(i, product_search_service.Product) + for i in responses) @pytest.mark.asyncio @@ -4079,8 +3555,8 @@ async def test_list_products_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products), "__call__", new_callable=mock.AsyncMock - ) as call: + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -4089,17 +3565,17 @@ async def test_list_products_async_pages(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4112,22 +3588,18 @@ async def test_list_products_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_products(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductRequest, - dict, - ], -) -def test_get_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4138,13 +3610,15 @@ def test_get_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.get_product(request) @@ -4156,10 +3630,10 @@ def test_get_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_get_product_non_empty_request_with_auto_populated_field(): @@ -4167,29 +3641,28 @@ def test_get_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetProductRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetProductRequest( - name="name_value", + name='name_value', ) - def test_get_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4208,9 +3681,7 @@ def test_get_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product] = mock_rpc request = {} client.get_product(request) @@ -4224,11 +3695,8 @@ def test_get_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4242,17 +3710,12 @@ async def test_get_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_product] = mock_rpc request = {} await client.get_product(request) @@ -4266,12 +3729,8 @@ async def test_get_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetProductRequest, -): +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4282,16 +3741,16 @@ async def test_get_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.get_product(request) # Establish that the underlying gRPC stub method was called. @@ -4302,17 +3761,16 @@ async def test_get_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_get_product_async_from_dict(): await test_get_product_async(request_type=dict) - def test_get_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4322,10 +3780,12 @@ def test_get_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: call.return_value = product_search_service.Product() client.get_product(request) @@ -4337,9 +3797,9 @@ def test_get_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -4352,13 +3812,13 @@ async def test_get_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.get_product(request) # Establish that the underlying gRPC stub method was called. @@ -4369,9 +3829,9 @@ async def test_get_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_product_flattened(): @@ -4380,13 +3840,15 @@ def test_get_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -4394,7 +3856,7 @@ def test_get_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -4408,10 +3870,9 @@ def test_get_product_flattened_error(): with pytest.raises(ValueError): client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_product_flattened_async(): client = ProductSearchAsyncClient( @@ -4419,17 +3880,17 @@ async def test_get_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -4437,10 +3898,9 @@ async def test_get_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -4452,18 +3912,15 @@ async def test_get_product_flattened_error_async(): with pytest.raises(ValueError): await client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductRequest, - dict, - ], -) -def test_update_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4474,13 +3931,15 @@ def test_update_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.update_product(request) @@ -4492,10 +3951,10 @@ def test_update_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_update_product_non_empty_request_with_auto_populated_field(): @@ -4503,24 +3962,25 @@ def test_update_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = product_search_service.UpdateProductRequest() + request = product_search_service.UpdateProductRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.update_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductRequest() - + assert args[0] == product_search_service.UpdateProductRequest( + ) def test_update_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4540,9 +4000,7 @@ def test_update_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} client.update_product(request) @@ -4556,11 +4014,8 @@ def test_update_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4574,17 +4029,12 @@ async def test_update_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.update_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.update_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.update_product] = mock_rpc request = {} await client.update_product(request) @@ -4598,12 +4048,8 @@ async def test_update_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.UpdateProductRequest, -): +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.UpdateProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4614,16 +4060,16 @@ async def test_update_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.update_product(request) # Establish that the underlying gRPC stub method was called. @@ -4634,17 +4080,16 @@ async def test_update_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_update_product_async_from_dict(): await test_update_product_async(request_type=dict) - def test_update_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4654,10 +4099,12 @@ def test_update_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductRequest() - request.product.name = "name_value" + request.product.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: call.return_value = product_search_service.Product() client.update_product(request) @@ -4669,9 +4116,9 @@ def test_update_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -4684,13 +4131,13 @@ async def test_update_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductRequest() - request.product.name = "name_value" + request.product.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.update_product(request) # Establish that the underlying gRPC stub method was called. @@ -4701,9 +4148,9 @@ async def test_update_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] def test_update_product_flattened(): @@ -4712,14 +4159,16 @@ def test_update_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_product( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -4727,10 +4176,10 @@ def test_update_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val @@ -4744,11 +4193,10 @@ def test_update_product_flattened_error(): with pytest.raises(ValueError): client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) - @pytest.mark.asyncio async def test_update_product_flattened_async(): client = ProductSearchAsyncClient( @@ -4756,18 +4204,18 @@ async def test_update_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_product( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -4775,13 +4223,12 @@ async def test_update_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val - @pytest.mark.asyncio async def test_update_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -4793,19 +4240,16 @@ async def test_update_product_flattened_error_async(): with pytest.raises(ValueError): await client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductRequest, - dict, - ], -) -def test_delete_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4816,7 +4260,9 @@ def test_delete_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_product(request) @@ -4836,29 +4282,28 @@ def test_delete_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteProductRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteProductRequest( - name="name_value", + name='name_value', ) - def test_delete_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4877,9 +4322,7 @@ def test_delete_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc request = {} client.delete_product(request) @@ -4893,11 +4336,8 @@ def test_delete_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4911,17 +4351,12 @@ async def test_delete_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_product] = mock_rpc request = {} await client.delete_product(request) @@ -4935,12 +4370,8 @@ async def test_delete_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteProductRequest, -): +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4951,7 +4382,9 @@ async def test_delete_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_product(request) @@ -4970,7 +4403,6 @@ async def test_delete_product_async( async def test_delete_product_async_from_dict(): await test_delete_product_async(request_type=dict) - def test_delete_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4980,10 +4412,12 @@ def test_delete_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = None client.delete_product(request) @@ -4995,9 +4429,9 @@ def test_delete_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5010,10 +4444,12 @@ async def test_delete_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product(request) @@ -5025,9 +4461,9 @@ async def test_delete_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_product_flattened(): @@ -5036,13 +4472,15 @@ def test_delete_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5050,7 +4488,7 @@ def test_delete_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -5064,10 +4502,9 @@ def test_delete_product_flattened_error(): with pytest.raises(ValueError): client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_product_flattened_async(): client = ProductSearchAsyncClient( @@ -5075,7 +4512,9 @@ async def test_delete_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -5083,7 +4522,7 @@ async def test_delete_product_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5091,10 +4530,9 @@ async def test_delete_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5106,18 +4544,15 @@ async def test_delete_product_flattened_error_async(): with pytest.raises(ValueError): await client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateReferenceImageRequest, - dict, - ], -) -def test_create_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateReferenceImageRequest, + dict, +]) +def test_create_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5129,12 +4564,12 @@ def test_create_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) response = client.create_reference_image(request) @@ -5146,8 +4581,8 @@ def test_create_reference_image(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' def test_create_reference_image_non_empty_request_with_auto_populated_field(): @@ -5155,33 +4590,30 @@ def test_create_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateReferenceImageRequest( - parent="parent_value", - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image_id='reference_image_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.create_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateReferenceImageRequest( - parent="parent_value", - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image_id='reference_image_id_value', ) - def test_create_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5196,19 +4628,12 @@ def test_create_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.create_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_reference_image] = mock_rpc request = {} client.create_reference_image(request) @@ -5221,11 +4646,8 @@ def test_create_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5239,17 +4661,12 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_reference_image] = mock_rpc request = {} await client.create_reference_image(request) @@ -5263,12 +4680,8 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateReferenceImageRequest, -): +async def test_create_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5280,15 +4693,13 @@ async def test_create_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) response = await client.create_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -5299,15 +4710,14 @@ async def test_create_reference_image_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.asyncio async def test_create_reference_image_async_from_dict(): await test_create_reference_image_async(request_type=dict) - def test_create_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5317,12 +4727,12 @@ def test_create_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateReferenceImageRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.create_reference_image(request) @@ -5334,9 +4744,9 @@ def test_create_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5349,15 +4759,13 @@ async def test_create_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateReferenceImageRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + type(client.transport.create_reference_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) await client.create_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -5368,9 +4776,9 @@ async def test_create_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_reference_image_flattened(): @@ -5380,16 +4788,16 @@ def test_create_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_reference_image( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) # Establish that the underlying call was made with the expected @@ -5397,13 +4805,13 @@ def test_create_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].reference_image - mock_val = product_search_service.ReferenceImage(name="name_value") + mock_val = product_search_service.ReferenceImage(name='name_value') assert arg == mock_val arg = args[0].reference_image_id - mock_val = "reference_image_id_value" + mock_val = 'reference_image_id_value' assert arg == mock_val @@ -5417,12 +4825,11 @@ def test_create_reference_image_flattened_error(): with pytest.raises(ValueError): client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) - @pytest.mark.asyncio async def test_create_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -5431,20 +4838,18 @@ async def test_create_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_reference_image( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) # Establish that the underlying call was made with the expected @@ -5452,16 +4857,15 @@ async def test_create_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].reference_image - mock_val = product_search_service.ReferenceImage(name="name_value") + mock_val = product_search_service.ReferenceImage(name='name_value') assert arg == mock_val arg = args[0].reference_image_id - mock_val = "reference_image_id_value" + mock_val = 'reference_image_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5473,20 +4877,17 @@ async def test_create_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteReferenceImageRequest, - dict, - ], -) -def test_delete_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteReferenceImageRequest, + dict, +]) +def test_delete_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5498,8 +4899,8 @@ def test_delete_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_reference_image(request) @@ -5519,31 +4920,28 @@ def test_delete_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteReferenceImageRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.delete_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteReferenceImageRequest( - name="name_value", + name='name_value', ) - def test_delete_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5558,19 +4956,12 @@ def test_delete_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.delete_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_reference_image] = mock_rpc request = {} client.delete_reference_image(request) @@ -5583,11 +4974,8 @@ def test_delete_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5601,17 +4989,12 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_reference_image] = mock_rpc request = {} await client.delete_reference_image(request) @@ -5625,12 +5008,8 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteReferenceImageRequest, -): +async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5642,8 +5021,8 @@ async def test_delete_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_reference_image(request) @@ -5662,7 +5041,6 @@ async def test_delete_reference_image_async( async def test_delete_reference_image_async_from_dict(): await test_delete_reference_image_async(request_type=dict) - def test_delete_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5672,12 +5050,12 @@ def test_delete_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = None client.delete_reference_image(request) @@ -5689,9 +5067,9 @@ def test_delete_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5704,12 +5082,12 @@ async def test_delete_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_reference_image(request) @@ -5721,9 +5099,9 @@ async def test_delete_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_reference_image_flattened(): @@ -5733,14 +5111,14 @@ def test_delete_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5748,7 +5126,7 @@ def test_delete_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -5762,10 +5140,9 @@ def test_delete_reference_image_flattened_error(): with pytest.raises(ValueError): client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -5774,8 +5151,8 @@ async def test_delete_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -5783,7 +5160,7 @@ async def test_delete_reference_image_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5791,10 +5168,9 @@ async def test_delete_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5806,18 +5182,15 @@ async def test_delete_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListReferenceImagesRequest, - dict, - ], -) -def test_list_reference_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListReferenceImagesRequest, + dict, +]) +def test_list_reference_images(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5829,12 +5202,12 @@ def test_list_reference_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse( page_size=951, - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_reference_images(request) @@ -5847,7 +5220,7 @@ def test_list_reference_images(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_reference_images_non_empty_request_with_auto_populated_field(): @@ -5855,33 +5228,30 @@ def test_list_reference_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListReferenceImagesRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_reference_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_reference_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListReferenceImagesRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_reference_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5896,19 +5266,12 @@ def test_list_reference_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_reference_images - in client._transport._wrapped_methods - ) + assert client._transport.list_reference_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reference_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_reference_images] = mock_rpc request = {} client.list_reference_images(request) @@ -5921,11 +5284,8 @@ def test_list_reference_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_reference_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5939,17 +5299,12 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_reference_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_reference_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_reference_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_reference_images] = mock_rpc request = {} await client.list_reference_images(request) @@ -5963,12 +5318,8 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_reference_images_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListReferenceImagesRequest, -): +async def test_list_reference_images_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListReferenceImagesRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5980,15 +5331,13 @@ async def test_list_reference_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse( + page_size=951, + next_page_token='next_page_token_value', + )) response = await client.list_reference_images(request) # Establish that the underlying gRPC stub method was called. @@ -6000,14 +5349,13 @@ async def test_list_reference_images_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesAsyncPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_reference_images_async_from_dict(): await test_list_reference_images_async(request_type=dict) - def test_list_reference_images_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6017,12 +5365,12 @@ def test_list_reference_images_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListReferenceImagesRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: call.return_value = product_search_service.ListReferenceImagesResponse() client.list_reference_images(request) @@ -6034,9 +5382,9 @@ def test_list_reference_images_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6049,15 +5397,13 @@ async def test_list_reference_images_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListReferenceImagesRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse() - ) + type(client.transport.list_reference_images), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse()) await client.list_reference_images(request) # Establish that the underlying gRPC stub method was called. @@ -6068,9 +5414,9 @@ async def test_list_reference_images_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_reference_images_flattened(): @@ -6080,14 +5426,14 @@ def test_list_reference_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_reference_images( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -6095,7 +5441,7 @@ def test_list_reference_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -6109,10 +5455,9 @@ def test_list_reference_images_flattened_error(): with pytest.raises(ValueError): client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_reference_images_flattened_async(): client = ProductSearchAsyncClient( @@ -6121,18 +5466,16 @@ async def test_list_reference_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_reference_images( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -6140,10 +5483,9 @@ async def test_list_reference_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_reference_images_flattened_error_async(): client = ProductSearchAsyncClient( @@ -6155,7 +5497,7 @@ async def test_list_reference_images_flattened_error_async(): with pytest.raises(ValueError): await client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) @@ -6167,8 +5509,8 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6177,17 +5519,17 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6202,7 +5544,9 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_reference_images(request={}, retry=retry, timeout=timeout) @@ -6212,11 +5556,8 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in results - ) - - + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in results) def test_list_reference_images_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6225,8 +5566,8 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6235,17 +5576,17 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6256,10 +5597,9 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_reference_images(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_reference_images_async_pager(): client = ProductSearchAsyncClient( @@ -6268,10 +5608,8 @@ async def test_list_reference_images_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_reference_images), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6280,17 +5618,17 @@ async def test_list_reference_images_async_pager(): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6300,18 +5638,15 @@ async def test_list_reference_images_async_pager(): ), RuntimeError, ) - async_pager = await client.list_reference_images( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_reference_images(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in responses - ) + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in responses) @pytest.mark.asyncio @@ -6322,10 +5657,8 @@ async def test_list_reference_images_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_reference_images), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6334,17 +5667,17 @@ async def test_list_reference_images_async_pages(): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6357,22 +5690,18 @@ async def test_list_reference_images_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_reference_images(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetReferenceImageRequest, - dict, - ], -) -def test_get_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetReferenceImageRequest, + dict, +]) +def test_get_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6384,12 +5713,12 @@ def test_get_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) response = client.get_reference_image(request) @@ -6401,8 +5730,8 @@ def test_get_reference_image(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' def test_get_reference_image_non_empty_request_with_auto_populated_field(): @@ -6410,31 +5739,28 @@ def test_get_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetReferenceImageRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.get_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetReferenceImageRequest( - name="name_value", + name='name_value', ) - def test_get_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6449,18 +5775,12 @@ def test_get_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_reference_image in client._transport._wrapped_methods - ) + assert client._transport.get_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_reference_image] = mock_rpc request = {} client.get_reference_image(request) @@ -6473,11 +5793,8 @@ def test_get_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -6491,17 +5808,12 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_reference_image] = mock_rpc request = {} await client.get_reference_image(request) @@ -6515,12 +5827,8 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetReferenceImageRequest, -): +async def test_get_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6532,15 +5840,13 @@ async def test_get_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) response = await client.get_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -6551,15 +5857,14 @@ async def test_get_reference_image_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.asyncio async def test_get_reference_image_async_from_dict(): await test_get_reference_image_async(request_type=dict) - def test_get_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6569,12 +5874,12 @@ def test_get_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.get_reference_image(request) @@ -6586,9 +5891,9 @@ def test_get_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6601,15 +5906,13 @@ async def test_get_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + type(client.transport.get_reference_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) await client.get_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -6620,9 +5923,9 @@ async def test_get_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_reference_image_flattened(): @@ -6632,14 +5935,14 @@ def test_get_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -6647,7 +5950,7 @@ def test_get_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -6661,10 +5964,9 @@ def test_get_reference_image_flattened_error(): with pytest.raises(ValueError): client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -6673,18 +5975,16 @@ async def test_get_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -6692,10 +5992,9 @@ async def test_get_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -6707,18 +6006,15 @@ async def test_get_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.AddProductToProductSetRequest, - dict, - ], -) -def test_add_product_to_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.AddProductToProductSetRequest, + dict, +]) +def test_add_product_to_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6730,8 +6026,8 @@ def test_add_product_to_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.add_product_to_product_set(request) @@ -6751,33 +6047,30 @@ def test_add_product_to_product_set_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.AddProductToProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.add_product_to_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.add_product_to_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.AddProductToProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - def test_add_product_to_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6792,19 +6085,12 @@ def test_add_product_to_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.add_product_to_product_set - in client._transport._wrapped_methods - ) + assert client._transport.add_product_to_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_product_to_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_product_to_product_set] = mock_rpc request = {} client.add_product_to_product_set(request) @@ -6817,11 +6103,8 @@ def test_add_product_to_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -6835,17 +6118,12 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.add_product_to_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.add_product_to_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.add_product_to_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.add_product_to_product_set] = mock_rpc request = {} await client.add_product_to_product_set(request) @@ -6859,12 +6137,8 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_add_product_to_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.AddProductToProductSetRequest, -): +async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.AddProductToProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6876,8 +6150,8 @@ async def test_add_product_to_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.add_product_to_product_set(request) @@ -6896,7 +6170,6 @@ async def test_add_product_to_product_set_async( async def test_add_product_to_product_set_async_from_dict(): await test_add_product_to_product_set_async(request_type=dict) - def test_add_product_to_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6906,12 +6179,12 @@ def test_add_product_to_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.AddProductToProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = None client.add_product_to_product_set(request) @@ -6923,9 +6196,9 @@ def test_add_product_to_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6938,12 +6211,12 @@ async def test_add_product_to_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.AddProductToProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.add_product_to_product_set(request) @@ -6955,9 +6228,9 @@ async def test_add_product_to_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_add_product_to_product_set_flattened(): @@ -6967,15 +6240,15 @@ def test_add_product_to_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.add_product_to_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -6983,10 +6256,10 @@ def test_add_product_to_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val @@ -7000,11 +6273,10 @@ def test_add_product_to_product_set_flattened_error(): with pytest.raises(ValueError): client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7013,8 +6285,8 @@ async def test_add_product_to_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -7022,8 +6294,8 @@ async def test_add_product_to_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.add_product_to_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7031,13 +6303,12 @@ async def test_add_product_to_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val - @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7049,19 +6320,16 @@ async def test_add_product_to_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.RemoveProductFromProductSetRequest, - dict, - ], -) -def test_remove_product_from_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.RemoveProductFromProductSetRequest, + dict, +]) +def test_remove_product_from_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7073,8 +6341,8 @@ def test_remove_product_from_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.remove_product_from_product_set(request) @@ -7094,33 +6362,30 @@ def test_remove_product_from_product_set_non_empty_request_with_auto_populated_f # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.RemoveProductFromProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.remove_product_from_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.remove_product_from_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.RemoveProductFromProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - def test_remove_product_from_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7135,19 +6400,12 @@ def test_remove_product_from_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.remove_product_from_product_set - in client._transport._wrapped_methods - ) + assert client._transport.remove_product_from_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_product_from_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_product_from_product_set] = mock_rpc request = {} client.remove_product_from_product_set(request) @@ -7160,11 +6418,8 @@ def test_remove_product_from_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7178,17 +6433,12 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.remove_product_from_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.remove_product_from_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.remove_product_from_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.remove_product_from_product_set] = mock_rpc request = {} await client.remove_product_from_product_set(request) @@ -7202,12 +6452,8 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_remove_product_from_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.RemoveProductFromProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7219,8 +6465,8 @@ async def test_remove_product_from_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.remove_product_from_product_set(request) @@ -7239,7 +6485,6 @@ async def test_remove_product_from_product_set_async( async def test_remove_product_from_product_set_async_from_dict(): await test_remove_product_from_product_set_async(request_type=dict) - def test_remove_product_from_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7249,12 +6494,12 @@ def test_remove_product_from_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.RemoveProductFromProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = None client.remove_product_from_product_set(request) @@ -7266,9 +6511,9 @@ def test_remove_product_from_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -7281,12 +6526,12 @@ async def test_remove_product_from_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.RemoveProductFromProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.remove_product_from_product_set(request) @@ -7298,9 +6543,9 @@ async def test_remove_product_from_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_remove_product_from_product_set_flattened(): @@ -7310,15 +6555,15 @@ def test_remove_product_from_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.remove_product_from_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7326,10 +6571,10 @@ def test_remove_product_from_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val @@ -7343,11 +6588,10 @@ def test_remove_product_from_product_set_flattened_error(): with pytest.raises(ValueError): client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7356,8 +6600,8 @@ async def test_remove_product_from_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -7365,8 +6609,8 @@ async def test_remove_product_from_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.remove_product_from_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7374,13 +6618,12 @@ async def test_remove_product_from_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val - @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7392,19 +6635,16 @@ async def test_remove_product_from_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsInProductSetRequest, - dict, - ], -) -def test_list_products_in_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsInProductSetRequest, + dict, +]) +def test_list_products_in_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7416,11 +6656,11 @@ def test_list_products_in_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_products_in_product_set(request) @@ -7432,7 +6672,7 @@ def test_list_products_in_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_products_in_product_set_non_empty_request_with_auto_populated_field(): @@ -7440,33 +6680,30 @@ def test_list_products_in_product_set_non_empty_request_with_auto_populated_fiel # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductsInProductSetRequest( - name="name_value", - page_token="page_token_value", + name='name_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_products_in_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_products_in_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductsInProductSetRequest( - name="name_value", - page_token="page_token_value", + name='name_value', + page_token='page_token_value', ) - def test_list_products_in_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7481,19 +6718,12 @@ def test_list_products_in_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_products_in_product_set - in client._transport._wrapped_methods - ) + assert client._transport.list_products_in_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_products_in_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products_in_product_set] = mock_rpc request = {} client.list_products_in_product_set(request) @@ -7506,11 +6736,8 @@ def test_list_products_in_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7524,17 +6751,12 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_products_in_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_products_in_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_products_in_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_products_in_product_set] = mock_rpc request = {} await client.list_products_in_product_set(request) @@ -7548,12 +6770,8 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_in_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductsInProductSetRequest, -): +async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductsInProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7565,14 +6783,12 @@ async def test_list_products_in_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse( + next_page_token='next_page_token_value', + )) response = await client.list_products_in_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -7583,14 +6799,13 @@ async def test_list_products_in_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_products_in_product_set_async_from_dict(): await test_list_products_in_product_set_async(request_type=dict) - def test_list_products_in_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7600,12 +6815,12 @@ def test_list_products_in_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsInProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: call.return_value = product_search_service.ListProductsInProductSetResponse() client.list_products_in_product_set(request) @@ -7617,9 +6832,9 @@ def test_list_products_in_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -7632,15 +6847,13 @@ async def test_list_products_in_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsInProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse() - ) + type(client.transport.list_products_in_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse()) await client.list_products_in_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -7651,9 +6864,9 @@ async def test_list_products_in_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_list_products_in_product_set_flattened(): @@ -7663,14 +6876,14 @@ def test_list_products_in_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_products_in_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -7678,7 +6891,7 @@ def test_list_products_in_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -7692,10 +6905,9 @@ def test_list_products_in_product_set_flattened_error(): with pytest.raises(ValueError): client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7704,18 +6916,16 @@ async def test_list_products_in_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_products_in_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -7723,10 +6933,9 @@ async def test_list_products_in_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7738,7 +6947,7 @@ async def test_list_products_in_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) @@ -7750,8 +6959,8 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7760,17 +6969,17 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7785,11 +6994,11 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), - ) - pager = client.list_products_in_product_set( - request={}, retry=retry, timeout=timeout + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), ) + pager = client.list_products_in_product_set(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7797,9 +7006,8 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) - - + assert all(isinstance(i, product_search_service.Product) + for i in results) def test_list_products_in_product_set_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7808,8 +7016,8 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7818,17 +7026,17 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7839,10 +7047,9 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_products_in_product_set(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_products_in_product_set_async_pager(): client = ProductSearchAsyncClient( @@ -7851,10 +7058,8 @@ async def test_list_products_in_product_set_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_products_in_product_set), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7863,17 +7068,17 @@ async def test_list_products_in_product_set_async_pager(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7883,16 +7088,15 @@ async def test_list_products_in_product_set_async_pager(): ), RuntimeError, ) - async_pager = await client.list_products_in_product_set( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_products_in_product_set(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.Product) for i in responses) + assert all(isinstance(i, product_search_service.Product) + for i in responses) @pytest.mark.asyncio @@ -7903,10 +7107,8 @@ async def test_list_products_in_product_set_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_products_in_product_set), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7915,17 +7117,17 @@ async def test_list_products_in_product_set_async_pages(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7938,22 +7140,18 @@ async def test_list_products_in_product_set_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_products_in_product_set(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ImportProductSetsRequest, - dict, - ], -) -def test_import_product_sets(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ImportProductSetsRequest, + dict, +]) +def test_import_product_sets(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7965,10 +7163,10 @@ def test_import_product_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -7986,31 +7184,28 @@ def test_import_product_sets_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ImportProductSetsRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.import_product_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ImportProductSetsRequest( - parent="parent_value", + parent='parent_value', ) - def test_import_product_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8025,18 +7220,12 @@ def test_import_product_sets_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.import_product_sets in client._transport._wrapped_methods - ) + assert client._transport.import_product_sets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_product_sets] = mock_rpc request = {} client.import_product_sets(request) @@ -8054,11 +7243,8 @@ def test_import_product_sets_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_import_product_sets_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -8072,17 +7258,12 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.import_product_sets - in client._client._transport._wrapped_methods - ) + assert client._client._transport.import_product_sets in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.import_product_sets - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.import_product_sets] = mock_rpc request = {} await client.import_product_sets(request) @@ -8101,12 +7282,8 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_import_product_sets_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ImportProductSetsRequest, -): +async def test_import_product_sets_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ImportProductSetsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8118,11 +7295,11 @@ async def test_import_product_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.import_product_sets(request) @@ -8140,7 +7317,6 @@ async def test_import_product_sets_async( async def test_import_product_sets_async_from_dict(): await test_import_product_sets_async(request_type=dict) - def test_import_product_sets_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8150,13 +7326,13 @@ def test_import_product_sets_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ImportProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -8167,9 +7343,9 @@ def test_import_product_sets_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -8182,15 +7358,13 @@ async def test_import_product_sets_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ImportProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) await client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -8201,9 +7375,9 @@ async def test_import_product_sets_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_import_product_sets_flattened(): @@ -8213,19 +7387,15 @@ def test_import_product_sets_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.import_product_sets( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) # Establish that the underlying call was made with the expected @@ -8233,14 +7403,10 @@ def test_import_product_sets_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].input_config - mock_val = product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ) + mock_val = product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')) assert arg == mock_val @@ -8254,15 +7420,10 @@ def test_import_product_sets_flattened_error(): with pytest.raises(ValueError): client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) - @pytest.mark.asyncio async def test_import_product_sets_flattened_async(): client = ProductSearchAsyncClient( @@ -8271,23 +7432,19 @@ async def test_import_product_sets_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.import_product_sets( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) # Establish that the underlying call was made with the expected @@ -8295,17 +7452,12 @@ async def test_import_product_sets_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].input_config - mock_val = product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ) + mock_val = product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')) assert arg == mock_val - @pytest.mark.asyncio async def test_import_product_sets_flattened_error_async(): client = ProductSearchAsyncClient( @@ -8317,23 +7469,16 @@ async def test_import_product_sets_flattened_error_async(): with pytest.raises(ValueError): await client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.PurgeProductsRequest, - dict, - ], -) -def test_purge_products(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.PurgeProductsRequest, + dict, +]) +def test_purge_products(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8344,9 +7489,11 @@ def test_purge_products(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.purge_products(request) # Establish that the underlying gRPC stub method was called. @@ -8364,29 +7511,28 @@ def test_purge_products_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.PurgeProductsRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.purge_products(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.PurgeProductsRequest( - parent="parent_value", + parent='parent_value', ) - def test_purge_products_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8405,9 +7551,7 @@ def test_purge_products_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.purge_products] = mock_rpc request = {} client.purge_products(request) @@ -8426,11 +7570,8 @@ def test_purge_products_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_purge_products_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_purge_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -8444,17 +7585,12 @@ async def test_purge_products_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.purge_products - in client._client._transport._wrapped_methods - ) + assert client._client._transport.purge_products in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.purge_products - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.purge_products] = mock_rpc request = {} await client.purge_products(request) @@ -8473,12 +7609,8 @@ async def test_purge_products_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_purge_products_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.PurgeProductsRequest, -): +async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=product_search_service.PurgeProductsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8489,10 +7621,12 @@ async def test_purge_products_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.purge_products(request) @@ -8510,7 +7644,6 @@ async def test_purge_products_async( async def test_purge_products_async_from_dict(): await test_purge_products_async(request_type=dict) - def test_purge_products_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8520,11 +7653,13 @@ def test_purge_products_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.PurgeProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.purge_products(request) # Establish that the underlying gRPC stub method was called. @@ -8535,9 +7670,9 @@ def test_purge_products_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -8550,13 +7685,13 @@ async def test_purge_products_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.PurgeProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) await client.purge_products(request) # Establish that the underlying gRPC stub method was called. @@ -8567,9 +7702,9 @@ async def test_purge_products_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_purge_products_flattened(): @@ -8578,13 +7713,15 @@ def test_purge_products_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.purge_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -8592,7 +7729,7 @@ def test_purge_products_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -8606,10 +7743,9 @@ def test_purge_products_flattened_error(): with pytest.raises(ValueError): client.purge_products( product_search_service.PurgeProductsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_purge_products_flattened_async(): client = ProductSearchAsyncClient( @@ -8617,17 +7753,19 @@ async def test_purge_products_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.purge_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -8635,10 +7773,9 @@ async def test_purge_products_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_purge_products_flattened_error_async(): client = ProductSearchAsyncClient( @@ -8650,7 +7787,7 @@ async def test_purge_products_flattened_error_async(): with pytest.raises(ValueError): await client.purge_products( product_search_service.PurgeProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -8668,18 +7805,12 @@ def test_create_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_product_set in client._transport._wrapped_methods - ) + assert client._transport.create_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_product_set] = mock_rpc request = {} client.create_product_set(request) @@ -8694,64 +7825,59 @@ def test_create_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_product_set_rest_required_fields( - request_type=product_search_service.CreateProductSetRequest, -): +def test_create_product_set_rest_required_fields(request_type=product_search_service.CreateProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product_set._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("product_set_id",)) + assert not set(unset_fields) - set(("product_set_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -8761,32 +7887,24 @@ def test_create_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("productSetId",)) - & set( - ( - "parent", - "productSet", - ) - ) - ) + assert set(unset_fields) == (set(("productSetId", )) & set(("parent", "productSet", ))) def test_create_product_set_rest_flattened(): @@ -8796,18 +7914,18 @@ def test_create_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) mock_args.update(sample_request) @@ -8817,7 +7935,7 @@ def test_create_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -8827,14 +7945,10 @@ def test_create_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/productSets" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/productSets" % client.transport._host, args[1]) -def test_create_product_set_rest_flattened_error(transport: str = "rest"): +def test_create_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8845,9 +7959,9 @@ def test_create_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) @@ -8869,12 +7983,8 @@ def test_list_product_sets_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_product_sets] = mock_rpc request = {} client.list_product_sets(request) @@ -8889,67 +7999,57 @@ def test_list_product_sets_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_product_sets_rest_required_fields( - request_type=product_search_service.ListProductSetsRequest, -): +def test_list_product_sets_rest_required_fields(request_type=product_search_service.ListProductSetsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_product_sets._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_product_sets._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -8957,37 +8057,27 @@ def test_list_product_sets_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductSetsResponse.pb( - return_value - ) + return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_product_sets(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_product_sets_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_product_sets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_product_sets_rest_flattened(): @@ -8997,16 +8087,16 @@ def test_list_product_sets_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -9016,7 +8106,7 @@ def test_list_product_sets_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9026,14 +8116,10 @@ def test_list_product_sets_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/productSets" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/productSets" % client.transport._host, args[1]) -def test_list_product_sets_rest_flattened_error(transport: str = "rest"): +def test_list_product_sets_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9044,20 +8130,20 @@ def test_list_product_sets_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_product_sets_rest_pager(transport: str = "rest"): +def test_list_product_sets_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductSetsResponse( @@ -9066,17 +8152,17 @@ def test_list_product_sets_rest_pager(transport: str = "rest"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -9089,25 +8175,24 @@ def test_list_product_sets_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductSetsResponse.to_json(x) for x in response - ) + response = tuple(product_search_service.ListProductSetsResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} pager = client.list_product_sets(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in results) + assert all(isinstance(i, product_search_service.ProductSet) + for i in results) pages = list(client.list_product_sets(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -9129,9 +8214,7 @@ def test_get_product_set_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product_set] = mock_rpc request = {} @@ -9147,60 +8230,55 @@ def test_get_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_product_set_rest_required_fields( - request_type=product_search_service.GetProductSetRequest, -): +def test_get_product_set_rest_required_fields(request_type=product_search_service.GetProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -9211,24 +8289,24 @@ def test_get_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_product_set_rest_flattened(): @@ -9238,18 +8316,16 @@ def test_get_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -9259,7 +8335,7 @@ def test_get_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9269,14 +8345,10 @@ def test_get_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_get_product_set_rest_flattened_error(transport: str = "rest"): +def test_get_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9287,7 +8359,7 @@ def test_get_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) @@ -9305,18 +8377,12 @@ def test_update_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_product_set in client._transport._wrapped_methods - ) + assert client._transport.update_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_product_set] = mock_rpc request = {} client.update_product_set(request) @@ -9331,59 +8397,54 @@ def test_update_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_product_set_rest_required_fields( - request_type=product_search_service.UpdateProductSetRequest, -): +def test_update_product_set_rest_required_fields(request_type=product_search_service.UpdateProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("update_mask", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9393,24 +8454,24 @@ def test_update_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_update_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.update_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("productSet",))) + assert set(unset_fields) == (set(("updateMask", )) & set(("productSet", ))) def test_update_product_set_rest_flattened(): @@ -9420,21 +8481,17 @@ def test_update_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } + sample_request = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/sample3'}} # get truthy value for each flattened field mock_args = dict( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) mock_args.update(sample_request) @@ -9444,7 +8501,7 @@ def test_update_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9454,14 +8511,10 @@ def test_update_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{product_set.name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{product_set.name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_update_product_set_rest_flattened_error(transport: str = "rest"): +def test_update_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9472,8 +8525,8 @@ def test_update_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) @@ -9491,18 +8544,12 @@ def test_delete_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_product_set in client._transport._wrapped_methods - ) + assert client._transport.delete_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_set] = mock_rpc request = {} client.delete_product_set(request) @@ -9517,85 +8564,80 @@ def test_delete_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_product_set_rest_required_fields( - request_type=product_search_service.DeleteProductSetRequest, -): +def test_delete_product_set_rest_required_fields(request_type=product_search_service.DeleteProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_product_set_rest_flattened(): @@ -9605,26 +8647,24 @@ def test_delete_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9634,14 +8674,10 @@ def test_delete_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_delete_product_set_rest_flattened_error(transport: str = "rest"): +def test_delete_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9652,7 +8688,7 @@ def test_delete_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) @@ -9674,9 +8710,7 @@ def test_create_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.create_product] = mock_rpc request = {} @@ -9692,64 +8726,59 @@ def test_create_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_product_rest_required_fields( - request_type=product_search_service.CreateProductRequest, -): +def test_create_product_rest_required_fields(request_type=product_search_service.CreateProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("product_id",)) + assert not set(unset_fields) - set(("product_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9759,32 +8788,24 @@ def test_create_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_product._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("productId",)) - & set( - ( - "parent", - "product", - ) - ) - ) + assert set(unset_fields) == (set(("productId", )) & set(("parent", "product", ))) def test_create_product_rest_flattened(): @@ -9794,18 +8815,18 @@ def test_create_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) mock_args.update(sample_request) @@ -9815,7 +8836,7 @@ def test_create_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9825,13 +8846,10 @@ def test_create_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/products" % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/products" % client.transport._host, args[1]) -def test_create_product_rest_flattened_error(transport: str = "rest"): +def test_create_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9842,9 +8860,9 @@ def test_create_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) @@ -9866,9 +8884,7 @@ def test_list_products_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} @@ -9884,67 +8900,57 @@ def test_list_products_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_products_rest_required_fields( - request_type=product_search_service.ListProductsRequest, -): +def test_list_products_rest_required_fields(request_type=product_search_service.ListProductsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -9955,32 +8961,24 @@ def test_list_products_rest_required_fields( return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_products_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_products._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_products_rest_flattened(): @@ -9990,16 +8988,16 @@ def test_list_products_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -10009,7 +9007,7 @@ def test_list_products_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10019,13 +9017,10 @@ def test_list_products_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/products" % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/products" % client.transport._host, args[1]) -def test_list_products_rest_flattened_error(transport: str = "rest"): +def test_list_products_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10036,20 +9031,20 @@ def test_list_products_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_products_rest_pager(transport: str = "rest"): +def test_list_products_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductsResponse( @@ -10058,17 +9053,17 @@ def test_list_products_rest_pager(transport: str = "rest"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -10081,25 +9076,24 @@ def test_list_products_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductsResponse.to_json(x) for x in response - ) + response = tuple(product_search_service.ListProductsResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} pager = client.list_products(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) + assert all(isinstance(i, product_search_service.Product) + for i in results) pages = list(client.list_products(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -10121,9 +9115,7 @@ def test_get_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product] = mock_rpc request = {} @@ -10139,60 +9131,55 @@ def test_get_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_product_rest_required_fields( - request_type=product_search_service.GetProductRequest, -): +def test_get_product_rest_required_fields(request_type=product_search_service.GetProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -10203,24 +9190,24 @@ def test_get_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_product_rest_flattened(): @@ -10230,16 +9217,16 @@ def test_get_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/products/sample3"} + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -10249,7 +9236,7 @@ def test_get_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10259,13 +9246,10 @@ def test_get_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/products/*}" % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_get_product_rest_flattened_error(transport: str = "rest"): +def test_get_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10276,7 +9260,7 @@ def test_get_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) @@ -10298,9 +9282,7 @@ def test_update_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} @@ -10316,59 +9298,54 @@ def test_update_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_product_rest_required_fields( - request_type=product_search_service.UpdateProductRequest, -): +def test_update_product_rest_required_fields(request_type=product_search_service.UpdateProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("update_mask", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10378,24 +9355,24 @@ def test_update_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_update_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.update_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("product",))) + assert set(unset_fields) == (set(("updateMask", )) & set(("product", ))) def test_update_product_rest_flattened(): @@ -10405,19 +9382,17 @@ def test_update_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } + sample_request = {'product': {'name': 'projects/sample1/locations/sample2/products/sample3'}} # get truthy value for each flattened field mock_args = dict( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) mock_args.update(sample_request) @@ -10427,7 +9402,7 @@ def test_update_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10437,14 +9412,10 @@ def test_update_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{product.name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{product.name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_update_product_rest_flattened_error(transport: str = "rest"): +def test_update_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10455,8 +9426,8 @@ def test_update_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) @@ -10478,9 +9449,7 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc request = {} @@ -10496,85 +9465,80 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_product_rest_required_fields( - request_type=product_search_service.DeleteProductRequest, -): +def test_delete_product_rest_required_fields(request_type=product_search_service.DeleteProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_product_rest_flattened(): @@ -10584,24 +9548,24 @@ def test_delete_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/products/sample3"} + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10611,13 +9575,10 @@ def test_delete_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/products/*}" % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_delete_product_rest_flattened_error(transport: str = "rest"): +def test_delete_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10628,7 +9589,7 @@ def test_delete_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) @@ -10646,19 +9607,12 @@ def test_create_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.create_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_reference_image] = mock_rpc request = {} client.create_reference_image(request) @@ -10673,64 +9627,59 @@ def test_create_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_reference_image_rest_required_fields( - request_type=product_search_service.CreateReferenceImageRequest, -): +def test_create_reference_image_rest_required_fields(request_type=product_search_service.CreateReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reference_image._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reference_image._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("reference_image_id",)) + assert not set(unset_fields) - set(("reference_image_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10740,32 +9689,24 @@ def test_create_reference_image_rest_required_fields( return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("referenceImageId",)) - & set( - ( - "parent", - "referenceImage", - ) - ) - ) + assert set(unset_fields) == (set(("referenceImageId", )) & set(("parent", "referenceImage", ))) def test_create_reference_image_rest_flattened(): @@ -10775,20 +9716,18 @@ def test_create_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) mock_args.update(sample_request) @@ -10798,7 +9737,7 @@ def test_create_reference_image_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10808,14 +9747,10 @@ def test_create_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/products/*}/referenceImages" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/products/*}/referenceImages" % client.transport._host, args[1]) -def test_create_reference_image_rest_flattened_error(transport: str = "rest"): +def test_create_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10826,9 +9761,9 @@ def test_create_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) @@ -10846,19 +9781,12 @@ def test_delete_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.delete_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_reference_image] = mock_rpc request = {} client.delete_reference_image(request) @@ -10873,85 +9801,80 @@ def test_delete_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_reference_image_rest_required_fields( - request_type=product_search_service.DeleteReferenceImageRequest, -): +def test_delete_reference_image_rest_required_fields(request_type=product_search_service.DeleteReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_reference_image_rest_flattened(): @@ -10961,26 +9884,24 @@ def test_delete_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/sample4'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10990,14 +9911,10 @@ def test_delete_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/products/*/referenceImages/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/products/*/referenceImages/*}" % client.transport._host, args[1]) -def test_delete_reference_image_rest_flattened_error(transport: str = "rest"): +def test_delete_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11008,7 +9925,7 @@ def test_delete_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) @@ -11026,19 +9943,12 @@ def test_list_reference_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_reference_images - in client._transport._wrapped_methods - ) + assert client._transport.list_reference_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reference_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_reference_images] = mock_rpc request = {} client.list_reference_images(request) @@ -11053,67 +9963,57 @@ def test_list_reference_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_reference_images_rest_required_fields( - request_type=product_search_service.ListReferenceImagesRequest, -): +def test_list_reference_images_rest_required_fields(request_type=product_search_service.ListReferenceImagesRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reference_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reference_images._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reference_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reference_images._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11121,37 +10021,27 @@ def test_list_reference_images_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_reference_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_reference_images_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_reference_images._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_reference_images_rest_flattened(): @@ -11161,18 +10051,16 @@ def test_list_reference_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -11180,11 +10068,9 @@ def test_list_reference_images_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11194,14 +10080,10 @@ def test_list_reference_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/products/*}/referenceImages" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/products/*}/referenceImages" % client.transport._host, args[1]) -def test_list_reference_images_rest_flattened_error(transport: str = "rest"): +def test_list_reference_images_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11212,20 +10094,20 @@ def test_list_reference_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_reference_images_rest_pager(transport: str = "rest"): +def test_list_reference_images_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListReferenceImagesResponse( @@ -11234,17 +10116,17 @@ def test_list_reference_images_rest_pager(transport: str = "rest"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -11257,30 +10139,24 @@ def test_list_reference_images_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListReferenceImagesResponse.to_json(x) - for x in response - ) + response = tuple(product_search_service.ListReferenceImagesResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} pager = client.list_reference_images(request=sample_request) results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in results - ) + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in results) pages = list(client.list_reference_images(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -11298,18 +10174,12 @@ def test_get_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_reference_image in client._transport._wrapped_methods - ) + assert client._transport.get_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_reference_image] = mock_rpc request = {} client.get_reference_image(request) @@ -11324,60 +10194,55 @@ def test_get_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_reference_image_rest_required_fields( - request_type=product_search_service.GetReferenceImageRequest, -): +def test_get_reference_image_rest_required_fields(request_type=product_search_service.GetReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11388,24 +10253,24 @@ def test_get_reference_image_rest_required_fields( return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_reference_image_rest_flattened(): @@ -11415,18 +10280,16 @@ def test_get_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/sample4'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -11436,7 +10299,7 @@ def test_get_reference_image_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11446,14 +10309,10 @@ def test_get_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/products/*/referenceImages/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/products/*/referenceImages/*}" % client.transport._host, args[1]) -def test_get_reference_image_rest_flattened_error(transport: str = "rest"): +def test_get_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11464,7 +10323,7 @@ def test_get_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) @@ -11482,19 +10341,12 @@ def test_add_product_to_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.add_product_to_product_set - in client._transport._wrapped_methods - ) + assert client._transport.add_product_to_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_product_to_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_product_to_product_set] = mock_rpc request = {} client.add_product_to_product_set(request) @@ -11509,9 +10361,7 @@ def test_add_product_to_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_add_product_to_product_set_rest_required_fields( - request_type=product_search_service.AddProductToProductSetRequest, -): +def test_add_product_to_product_set_rest_required_fields(request_type=product_search_service.AddProductToProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} @@ -11519,88 +10369,77 @@ def test_add_product_to_product_set_rest_required_fields( request_init["product"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_product_to_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_product_to_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["product"] = "product_value" + jsonified_request["name"] = 'name_value' + jsonified_request["product"] = 'product_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_product_to_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_product_to_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" + assert jsonified_request["product"] == 'product_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_product_to_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_add_product_to_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.add_product_to_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "product", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "product", ))) def test_add_product_to_product_set_rest_flattened(): @@ -11610,27 +10449,25 @@ def test_add_product_to_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11640,14 +10477,10 @@ def test_add_product_to_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/productSets/*}:addProduct" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/productSets/*}:addProduct" % client.transport._host, args[1]) -def test_add_product_to_product_set_rest_flattened_error(transport: str = "rest"): +def test_add_product_to_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11658,8 +10491,8 @@ def test_add_product_to_product_set_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) @@ -11677,19 +10510,12 @@ def test_remove_product_from_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.remove_product_from_product_set - in client._transport._wrapped_methods - ) + assert client._transport.remove_product_from_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_product_from_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_product_from_product_set] = mock_rpc request = {} client.remove_product_from_product_set(request) @@ -11704,9 +10530,7 @@ def test_remove_product_from_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_remove_product_from_product_set_rest_required_fields( - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +def test_remove_product_from_product_set_rest_required_fields(request_type=product_search_service.RemoveProductFromProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} @@ -11714,90 +10538,77 @@ def test_remove_product_from_product_set_rest_required_fields( request_init["product"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_product_from_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_product_from_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["product"] = "product_value" + jsonified_request["name"] = 'name_value' + jsonified_request["product"] = 'product_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_product_from_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_product_from_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" + assert jsonified_request["product"] == 'product_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_product_from_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_remove_product_from_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) - unset_fields = transport.remove_product_from_product_set._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "product", - ) - ) - ) + unset_fields = transport.remove_product_from_product_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "product", ))) def test_remove_product_from_product_set_rest_flattened(): @@ -11807,27 +10618,25 @@ def test_remove_product_from_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11837,14 +10646,10 @@ def test_remove_product_from_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/productSets/*}:removeProduct" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/productSets/*}:removeProduct" % client.transport._host, args[1]) -def test_remove_product_from_product_set_rest_flattened_error(transport: str = "rest"): +def test_remove_product_from_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11855,8 +10660,8 @@ def test_remove_product_from_product_set_rest_flattened_error(transport: str = " with pytest.raises(ValueError): client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) @@ -11874,19 +10679,12 @@ def test_list_products_in_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_products_in_product_set - in client._transport._wrapped_methods - ) + assert client._transport.list_products_in_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_products_in_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products_in_product_set] = mock_rpc request = {} client.list_products_in_product_set(request) @@ -11901,67 +10699,57 @@ def test_list_products_in_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_products_in_product_set_rest_required_fields( - request_type=product_search_service.ListProductsInProductSetRequest, -): +def test_list_products_in_product_set_rest_required_fields(request_type=product_search_service.ListProductsInProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products_in_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products_in_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products_in_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products_in_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("page_size", "page_token", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11969,37 +10757,27 @@ def test_list_products_in_product_set_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products_in_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_products_in_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_products_in_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("name",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) def test_list_products_in_product_set_rest_flattened(): @@ -12009,18 +10787,16 @@ def test_list_products_in_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -12028,11 +10804,9 @@ def test_list_products_in_product_set_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -12042,14 +10816,10 @@ def test_list_products_in_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/productSets/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/locations/*/productSets/*}/products" % client.transport._host, args[1]) -def test_list_products_in_product_set_rest_flattened_error(transport: str = "rest"): +def test_list_products_in_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12060,20 +10830,20 @@ def test_list_products_in_product_set_rest_flattened_error(transport: str = "res with pytest.raises(ValueError): client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) -def test_list_products_in_product_set_rest_pager(transport: str = "rest"): +def test_list_products_in_product_set_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductsInProductSetResponse( @@ -12082,17 +10852,17 @@ def test_list_products_in_product_set_rest_pager(transport: str = "rest"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -12105,28 +10875,24 @@ def test_list_products_in_product_set_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductsInProductSetResponse.to_json(x) - for x in response - ) + response = tuple(product_search_service.ListProductsInProductSetResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} pager = client.list_products_in_product_set(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) + assert all(isinstance(i, product_search_service.Product) + for i in results) pages = list(client.list_products_in_product_set(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -12144,18 +10910,12 @@ def test_import_product_sets_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.import_product_sets in client._transport._wrapped_methods - ) + assert client._transport.import_product_sets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_product_sets] = mock_rpc request = {} client.import_product_sets(request) @@ -12174,94 +10934,81 @@ def test_import_product_sets_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_import_product_sets_rest_required_fields( - request_type=product_search_service.ImportProductSetsRequest, -): +def test_import_product_sets_rest_required_fields(request_type=product_search_service.ImportProductSetsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_product_sets._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_product_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.import_product_sets(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_import_product_sets_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.import_product_sets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("parent", "inputConfig", ))) def test_import_product_sets_rest_flattened(): @@ -12271,21 +11018,17 @@ def test_import_product_sets_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) mock_args.update(sample_request) @@ -12293,7 +11036,7 @@ def test_import_product_sets_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -12303,14 +11046,10 @@ def test_import_product_sets_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/productSets:import" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/productSets:import" % client.transport._host, args[1]) -def test_import_product_sets_rest_flattened_error(transport: str = "rest"): +def test_import_product_sets_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12321,12 +11060,8 @@ def test_import_product_sets_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) @@ -12348,9 +11083,7 @@ def test_purge_products_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.purge_products] = mock_rpc request = {} @@ -12370,86 +11103,81 @@ def test_purge_products_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_purge_products_rest_required_fields( - request_type=product_search_service.PurgeProductsRequest, -): +def test_purge_products_rest_required_fields(request_type=product_search_service.PurgeProductsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).purge_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_products._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).purge_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_products._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.purge_products(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_purge_products_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.purge_products._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) + assert set(unset_fields) == (set(()) & set(("parent", ))) def test_purge_products_rest_flattened(): @@ -12459,16 +11187,16 @@ def test_purge_products_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -12476,7 +11204,7 @@ def test_purge_products_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -12486,14 +11214,10 @@ def test_purge_products_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/products:purge" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/products:purge" % client.transport._host, args[1]) -def test_purge_products_rest_flattened_error(transport: str = "rest"): +def test_purge_products_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12504,7 +11228,7 @@ def test_purge_products_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.purge_products( product_search_service.PurgeProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -12546,7 +11270,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ProductSearchClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -12568,7 +11293,6 @@ def test_transport_instance(): client = ProductSearchClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( @@ -12583,23 +11307,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - transports.ProductSearchRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + transports.ProductSearchRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ProductSearchClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -12609,7 +11328,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -12624,8 +11344,8 @@ def test_create_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.create_product_set(request=None) @@ -12647,8 +11367,8 @@ def test_list_product_sets_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: call.return_value = product_search_service.ListProductSetsResponse() client.list_product_sets(request=None) @@ -12669,7 +11389,9 @@ def test_get_product_set_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.get_product_set(request=None) @@ -12691,8 +11413,8 @@ def test_update_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.update_product_set(request=None) @@ -12714,8 +11436,8 @@ def test_delete_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = None client.delete_product_set(request=None) @@ -12736,7 +11458,9 @@ def test_create_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: call.return_value = product_search_service.Product() client.create_product(request=None) @@ -12757,7 +11481,9 @@ def test_list_products_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: call.return_value = product_search_service.ListProductsResponse() client.list_products(request=None) @@ -12778,7 +11504,9 @@ def test_get_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: call.return_value = product_search_service.Product() client.get_product(request=None) @@ -12799,7 +11527,9 @@ def test_update_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: call.return_value = product_search_service.Product() client.update_product(request=None) @@ -12820,7 +11550,9 @@ def test_delete_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = None client.delete_product(request=None) @@ -12842,8 +11574,8 @@ def test_create_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.create_reference_image(request=None) @@ -12865,8 +11597,8 @@ def test_delete_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = None client.delete_reference_image(request=None) @@ -12888,8 +11620,8 @@ def test_list_reference_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: call.return_value = product_search_service.ListReferenceImagesResponse() client.list_reference_images(request=None) @@ -12911,8 +11643,8 @@ def test_get_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.get_reference_image(request=None) @@ -12934,8 +11666,8 @@ def test_add_product_to_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = None client.add_product_to_product_set(request=None) @@ -12957,8 +11689,8 @@ def test_remove_product_from_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = None client.remove_product_from_product_set(request=None) @@ -12980,8 +11712,8 @@ def test_list_products_in_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: call.return_value = product_search_service.ListProductsInProductSetResponse() client.list_products_in_product_set(request=None) @@ -13003,9 +11735,9 @@ def test_import_product_sets_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.import_product_sets(request=None) # Establish that the underlying stub method was called. @@ -13025,8 +11757,10 @@ def test_purge_products_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.purge_products(request=None) # Establish that the underlying stub method was called. @@ -13046,7 +11780,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -13062,15 +11797,13 @@ async def test_create_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.create_product_set(request=None) # Establish that the underlying stub method was called. @@ -13092,14 +11825,12 @@ async def test_list_product_sets_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse( + next_page_token='next_page_token_value', + )) await client.list_product_sets(request=None) # Establish that the underlying stub method was called. @@ -13120,14 +11851,14 @@ async def test_get_product_set_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.get_product_set(request=None) # Establish that the underlying stub method was called. @@ -13149,15 +11880,13 @@ async def test_update_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.update_product_set(request=None) # Establish that the underlying stub method was called. @@ -13179,8 +11908,8 @@ async def test_delete_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product_set(request=None) @@ -13203,16 +11932,16 @@ async def test_create_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.create_product(request=None) # Establish that the underlying stub method was called. @@ -13233,13 +11962,13 @@ async def test_list_products_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) await client.list_products(request=None) # Establish that the underlying stub method was called. @@ -13260,16 +11989,16 @@ async def test_get_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.get_product(request=None) # Establish that the underlying stub method was called. @@ -13290,16 +12019,16 @@ async def test_update_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.update_product(request=None) # Establish that the underlying stub method was called. @@ -13320,7 +12049,9 @@ async def test_delete_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product(request=None) @@ -13344,15 +12075,13 @@ async def test_create_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) await client.create_reference_image(request=None) # Establish that the underlying stub method was called. @@ -13374,8 +12103,8 @@ async def test_delete_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_reference_image(request=None) @@ -13399,15 +12128,13 @@ async def test_list_reference_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse( + page_size=951, + next_page_token='next_page_token_value', + )) await client.list_reference_images(request=None) # Establish that the underlying stub method was called. @@ -13429,15 +12156,13 @@ async def test_get_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) await client.get_reference_image(request=None) # Establish that the underlying stub method was called. @@ -13459,8 +12184,8 @@ async def test_add_product_to_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.add_product_to_product_set(request=None) @@ -13484,8 +12209,8 @@ async def test_remove_product_from_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.remove_product_from_product_set(request=None) @@ -13509,14 +12234,12 @@ async def test_list_products_in_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse( + next_page_token='next_page_token_value', + )) await client.list_products_in_product_set(request=None) # Establish that the underlying stub method was called. @@ -13538,11 +12261,11 @@ async def test_import_product_sets_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.import_product_sets(request=None) @@ -13564,10 +12287,12 @@ async def test_purge_products_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.purge_products(request=None) @@ -13586,23 +12311,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_create_product_set_rest_bad_request( - request_type=product_search_service.CreateProductSetRequest, -): +def test_create_product_set_rest_bad_request(request_type=product_search_service.CreateProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13611,43 +12333,25 @@ def test_create_product_set_rest_bad_request( client.create_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductSetRequest, + dict, +]) def test_create_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["product_set"] = { - "name": "name_value", - "display_name": "display_name_value", - "index_time": {"seconds": 751, "nanos": 543}, - "index_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["product_set"] = {'name': 'name_value', 'display_name': 'display_name_value', 'index_time': {'seconds': 751, 'nanos': 543}, 'index_error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.CreateProductSetRequest.meta.fields[ - "product_set" - ] + test_field = product_search_service.CreateProductSetRequest.meta.fields["product_set"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13661,7 +12365,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -13675,7 +12379,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product_set"].items(): # pragma: NO COVER + for field, value in request_init["product_set"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13690,16 +12394,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -13712,11 +12412,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13726,44 +12426,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_create_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateProductSetRequest.pb( - product_search_service.CreateProductSetRequest() - ) + pb_message = product_search_service.CreateProductSetRequest.pb(product_search_service.CreateProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13774,13 +12464,11 @@ def test_create_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.CreateProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -13788,36 +12476,27 @@ def test_create_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.create_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_product_sets_rest_bad_request( - request_type=product_search_service.ListProductSetsRequest, -): +def test_list_product_sets_rest_bad_request(request_type=product_search_service.ListProductSetsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13826,27 +12505,25 @@ def test_list_product_sets_rest_bad_request( client.list_product_sets(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductSetsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductSetsRequest, + dict, +]) def test_list_product_sets_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -13856,43 +12533,33 @@ def test_list_product_sets_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_product_sets(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_product_sets_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_product_sets" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_list_product_sets_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_product_sets" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_product_sets") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_product_sets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_product_sets") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductSetsRequest.pb( - product_search_service.ListProductSetsRequest() - ) + pb_message = product_search_service.ListProductSetsRequest.pb(product_search_service.ListProductSetsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13903,53 +12570,39 @@ def test_list_product_sets_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductSetsResponse.to_json( - product_search_service.ListProductSetsResponse() - ) + return_value = product_search_service.ListProductSetsResponse.to_json(product_search_service.ListProductSetsResponse()) req.return_value.content = return_value request = product_search_service.ListProductSetsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductSetsResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductSetsResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductSetsResponse(), metadata - client.list_product_sets( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_product_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_product_set_rest_bad_request( - request_type=product_search_service.GetProductSetRequest, -): +def test_get_product_set_rest_bad_request(request_type=product_search_service.GetProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13958,28 +12611,26 @@ def test_get_product_set_rest_bad_request( client.get_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductSetRequest, + dict, +]) def test_get_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13989,44 +12640,34 @@ def test_get_product_set_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_get_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetProductSetRequest.pb( - product_search_service.GetProductSetRequest() - ) + pb_message = product_search_service.GetProductSetRequest.pb(product_search_service.GetProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14037,13 +12678,11 @@ def test_get_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.GetProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14051,40 +12690,27 @@ def test_get_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.get_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_product_set_rest_bad_request( - request_type=product_search_service.UpdateProductSetRequest, -): +def test_update_product_set_rest_bad_request(request_type=product_search_service.UpdateProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } + request_init = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14093,47 +12719,25 @@ def test_update_product_set_rest_bad_request( client.update_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductSetRequest, + dict, +]) def test_update_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } - request_init["product_set"] = { - "name": "projects/sample1/locations/sample2/productSets/sample3", - "display_name": "display_name_value", - "index_time": {"seconds": 751, "nanos": 543}, - "index_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - } + request_init = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/sample3'}} + request_init["product_set"] = {'name': 'projects/sample1/locations/sample2/productSets/sample3', 'display_name': 'display_name_value', 'index_time': {'seconds': 751, 'nanos': 543}, 'index_error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.UpdateProductSetRequest.meta.fields[ - "product_set" - ] + test_field = product_search_service.UpdateProductSetRequest.meta.fields["product_set"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -14147,7 +12751,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14161,7 +12765,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product_set"].items(): # pragma: NO COVER + for field, value in request_init["product_set"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14176,16 +12780,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14198,11 +12798,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -14212,44 +12812,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_update_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_update_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_update_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_update_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.UpdateProductSetRequest.pb( - product_search_service.UpdateProductSetRequest() - ) + pb_message = product_search_service.UpdateProductSetRequest.pb(product_search_service.UpdateProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14260,13 +12850,11 @@ def test_update_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.UpdateProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14274,36 +12862,27 @@ def test_update_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.update_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_product_set_rest_bad_request( - request_type=product_search_service.DeleteProductSetRequest, -): +def test_delete_product_set_rest_bad_request(request_type=product_search_service.DeleteProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14312,32 +12891,30 @@ def test_delete_product_set_rest_bad_request( client.delete_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductSetRequest, + dict, +]) def test_delete_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product_set(request) @@ -14350,23 +12927,15 @@ def test_delete_product_set_rest_call_success(request_type): def test_delete_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteProductSetRequest.pb( - product_search_service.DeleteProductSetRequest() - ) + pb_message = product_search_service.DeleteProductSetRequest.pb(product_search_service.DeleteProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14379,40 +12948,31 @@ def test_delete_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_create_product_rest_bad_request( - request_type=product_search_service.CreateProductRequest, -): +def test_create_product_rest_bad_request(request_type=product_search_service.CreateProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14421,27 +12981,19 @@ def test_create_product_rest_bad_request( client.create_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductRequest, + dict, +]) def test_create_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["product"] = { - "name": "name_value", - "display_name": "display_name_value", - "description": "description_value", - "product_category": "product_category_value", - "product_labels": [{"key": "key_value", "value": "value_value"}], - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["product"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'product_category': 'product_category_value', 'product_labels': [{'key': 'key_value', 'value': 'value_value'}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -14461,7 +13013,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14475,7 +13027,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER + for field, value in request_init["product"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14490,16 +13042,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14512,13 +13060,13 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -14528,46 +13076,36 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_create_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateProductRequest.pb( - product_search_service.CreateProductRequest() - ) + pb_message = product_search_service.CreateProductRequest.pb(product_search_service.CreateProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14578,13 +13116,11 @@ def test_create_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.CreateProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14592,36 +13128,27 @@ def test_create_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.create_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_products_rest_bad_request( - request_type=product_search_service.ListProductsRequest, -): +def test_list_products_rest_bad_request(request_type=product_search_service.ListProductsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14630,27 +13157,25 @@ def test_list_products_rest_bad_request( client.list_products(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsRequest, + dict, +]) def test_list_products_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -14660,43 +13185,33 @@ def test_list_products_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_products_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_products" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_list_products_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_products" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_products") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductsRequest.pb( - product_search_service.ListProductsRequest() - ) + pb_message = product_search_service.ListProductsRequest.pb(product_search_service.ListProductsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14707,53 +13222,39 @@ def test_list_products_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductsResponse.to_json( - product_search_service.ListProductsResponse() - ) + return_value = product_search_service.ListProductsResponse.to_json(product_search_service.ListProductsResponse()) req.return_value.content = return_value request = product_search_service.ListProductsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductsResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductsResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductsResponse(), metadata - client.list_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_product_rest_bad_request( - request_type=product_search_service.GetProductRequest, -): +def test_get_product_rest_bad_request(request_type=product_search_service.GetProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14762,30 +13263,28 @@ def test_get_product_rest_bad_request( client.get_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductRequest, + dict, +]) def test_get_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -14795,46 +13294,36 @@ def test_get_product_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_get_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetProductRequest.pb( - product_search_service.GetProductRequest() - ) + pb_message = product_search_service.GetProductRequest.pb(product_search_service.GetProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14845,13 +13334,11 @@ def test_get_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.GetProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14859,38 +13346,27 @@ def test_get_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.get_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_product_rest_bad_request( - request_type=product_search_service.UpdateProductRequest, -): +def test_update_product_rest_bad_request(request_type=product_search_service.UpdateProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } + request_init = {'product': {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14899,29 +13375,19 @@ def test_update_product_rest_bad_request( client.update_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductRequest, + dict, +]) def test_update_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } - request_init["product"] = { - "name": "projects/sample1/locations/sample2/products/sample3", - "display_name": "display_name_value", - "description": "description_value", - "product_category": "product_category_value", - "product_labels": [{"key": "key_value", "value": "value_value"}], - } + request_init = {'product': {'name': 'projects/sample1/locations/sample2/products/sample3'}} + request_init["product"] = {'name': 'projects/sample1/locations/sample2/products/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'product_category': 'product_category_value', 'product_labels': [{'key': 'key_value', 'value': 'value_value'}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -14941,7 +13407,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14955,7 +13421,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER + for field, value in request_init["product"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14970,16 +13436,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14992,13 +13454,13 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -15008,46 +13470,36 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_update_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_update_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_update_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_update_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.UpdateProductRequest.pb( - product_search_service.UpdateProductRequest() - ) + pb_message = product_search_service.UpdateProductRequest.pb(product_search_service.UpdateProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15058,13 +13510,11 @@ def test_update_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.UpdateProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -15072,36 +13522,27 @@ def test_update_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.update_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_product_rest_bad_request( - request_type=product_search_service.DeleteProductRequest, -): +def test_delete_product_rest_bad_request(request_type=product_search_service.DeleteProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15110,32 +13551,30 @@ def test_delete_product_rest_bad_request( client.delete_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductRequest, + dict, +]) def test_delete_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product(request) @@ -15148,23 +13587,15 @@ def test_delete_product_rest_call_success(request_type): def test_delete_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_product") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteProductRequest.pb( - product_search_service.DeleteProductRequest() - ) + pb_message = product_search_service.DeleteProductRequest.pb(product_search_service.DeleteProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15177,40 +13608,31 @@ def test_delete_product_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_create_reference_image_rest_bad_request( - request_type=product_search_service.CreateReferenceImageRequest, -): +def test_create_reference_image_rest_bad_request(request_type=product_search_service.CreateReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15219,38 +13641,25 @@ def test_create_reference_image_rest_bad_request( client.create_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateReferenceImageRequest, + dict, +]) def test_create_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} - request_init["reference_image"] = { - "name": "name_value", - "uri": "uri_value", - "bounding_polys": [ - { - "vertices": [{"x": 120, "y": 121}], - "normalized_vertices": [{"x": 0.12, "y": 0.121}], - } - ], - } + request_init = {'parent': 'projects/sample1/locations/sample2/products/sample3'} + request_init["reference_image"] = {'name': 'name_value', 'uri': 'uri_value', 'bounding_polys': [{'vertices': [{'x': 120, 'y': 121}], 'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.CreateReferenceImageRequest.meta.fields[ - "reference_image" - ] + test_field = product_search_service.CreateReferenceImageRequest.meta.fields["reference_image"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -15264,7 +13673,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -15278,7 +13687,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["reference_image"].items(): # pragma: NO COVER + for field, value in request_init["reference_image"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -15293,16 +13702,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -15315,11 +13720,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) # Wrap the value into a proper Response obj @@ -15329,45 +13734,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_reference_image(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_reference_image" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_create_reference_image_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_reference_image") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_reference_image_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_reference_image") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateReferenceImageRequest.pb( - product_search_service.CreateReferenceImageRequest() - ) + pb_message = product_search_service.CreateReferenceImageRequest.pb(product_search_service.CreateReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15378,55 +13772,39 @@ def test_create_reference_image_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ReferenceImage.to_json( - product_search_service.ReferenceImage() - ) + return_value = product_search_service.ReferenceImage.to_json(product_search_service.ReferenceImage()) req.return_value.content = return_value request = product_search_service.CreateReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ReferenceImage() - post_with_metadata.return_value = ( - product_search_service.ReferenceImage(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ReferenceImage(), metadata - client.create_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_reference_image_rest_bad_request( - request_type=product_search_service.DeleteReferenceImageRequest, -): +def test_delete_reference_image_rest_bad_request(request_type=product_search_service.DeleteReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15435,34 +13813,30 @@ def test_delete_reference_image_rest_bad_request( client.delete_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteReferenceImageRequest, + dict, +]) def test_delete_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_reference_image(request) @@ -15475,23 +13849,15 @@ def test_delete_reference_image_rest_call_success(request_type): def test_delete_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_reference_image") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteReferenceImageRequest.pb( - product_search_service.DeleteReferenceImageRequest() - ) + pb_message = product_search_service.DeleteReferenceImageRequest.pb(product_search_service.DeleteReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15504,40 +13870,31 @@ def test_delete_reference_image_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_list_reference_images_rest_bad_request( - request_type=product_search_service.ListReferenceImagesRequest, -): +def test_list_reference_images_rest_bad_request(request_type=product_search_service.ListReferenceImagesRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15546,28 +13903,26 @@ def test_list_reference_images_rest_bad_request( client.list_reference_images(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListReferenceImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListReferenceImagesRequest, + dict, +]) def test_list_reference_images_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", + page_size=951, + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -15575,11 +13930,9 @@ def test_list_reference_images_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_reference_images(request) @@ -15587,37 +13940,26 @@ def test_list_reference_images_rest_call_success(request_type): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_reference_images_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_reference_images" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_list_reference_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_reference_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_reference_images") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_reference_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_reference_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListReferenceImagesRequest.pb( - product_search_service.ListReferenceImagesRequest() - ) + pb_message = product_search_service.ListReferenceImagesRequest.pb(product_search_service.ListReferenceImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15628,55 +13970,39 @@ def test_list_reference_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListReferenceImagesResponse.to_json( - product_search_service.ListReferenceImagesResponse() - ) + return_value = product_search_service.ListReferenceImagesResponse.to_json(product_search_service.ListReferenceImagesResponse()) req.return_value.content = return_value request = product_search_service.ListReferenceImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListReferenceImagesResponse() - post_with_metadata.return_value = ( - product_search_service.ListReferenceImagesResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListReferenceImagesResponse(), metadata - client.list_reference_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_reference_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_reference_image_rest_bad_request( - request_type=product_search_service.GetReferenceImageRequest, -): +def test_get_reference_image_rest_bad_request(request_type=product_search_service.GetReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15685,30 +14011,26 @@ def test_get_reference_image_rest_bad_request( client.get_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetReferenceImageRequest, + dict, +]) def test_get_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) # Wrap the value into a proper Response obj @@ -15718,45 +14040,34 @@ def test_get_reference_image_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_reference_image(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_reference_image" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_get_reference_image_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_reference_image") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_reference_image_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_reference_image") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetReferenceImageRequest.pb( - product_search_service.GetReferenceImageRequest() - ) + pb_message = product_search_service.GetReferenceImageRequest.pb(product_search_service.GetReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15767,53 +14078,39 @@ def test_get_reference_image_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ReferenceImage.to_json( - product_search_service.ReferenceImage() - ) + return_value = product_search_service.ReferenceImage.to_json(product_search_service.ReferenceImage()) req.return_value.content = return_value request = product_search_service.GetReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ReferenceImage() - post_with_metadata.return_value = ( - product_search_service.ReferenceImage(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ReferenceImage(), metadata - client.get_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_add_product_to_product_set_rest_bad_request( - request_type=product_search_service.AddProductToProductSetRequest, -): +def test_add_product_to_product_set_rest_bad_request(request_type=product_search_service.AddProductToProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15822,32 +14119,30 @@ def test_add_product_to_product_set_rest_bad_request( client.add_product_to_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.AddProductToProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.AddProductToProductSetRequest, + dict, +]) def test_add_product_to_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_product_to_product_set(request) @@ -15860,23 +14155,15 @@ def test_add_product_to_product_set_rest_call_success(request_type): def test_add_product_to_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_add_product_to_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_add_product_to_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.AddProductToProductSetRequest.pb( - product_search_service.AddProductToProductSetRequest() - ) + pb_message = product_search_service.AddProductToProductSetRequest.pb(product_search_service.AddProductToProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15889,40 +14176,31 @@ def test_add_product_to_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.AddProductToProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.add_product_to_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.add_product_to_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_remove_product_from_product_set_rest_bad_request( - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +def test_remove_product_from_product_set_rest_bad_request(request_type=product_search_service.RemoveProductFromProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15931,32 +14209,30 @@ def test_remove_product_from_product_set_rest_bad_request( client.remove_product_from_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.RemoveProductFromProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.RemoveProductFromProductSetRequest, + dict, +]) def test_remove_product_from_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_product_from_product_set(request) @@ -15969,23 +14245,15 @@ def test_remove_product_from_product_set_rest_call_success(request_type): def test_remove_product_from_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_remove_product_from_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_remove_product_from_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.RemoveProductFromProductSetRequest.pb( - product_search_service.RemoveProductFromProductSetRequest() - ) + pb_message = product_search_service.RemoveProductFromProductSetRequest.pb(product_search_service.RemoveProductFromProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15998,40 +14266,31 @@ def test_remove_product_from_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.RemoveProductFromProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.remove_product_from_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.remove_product_from_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_list_products_in_product_set_rest_bad_request( - request_type=product_search_service.ListProductsInProductSetRequest, -): +def test_list_products_in_product_set_rest_bad_request(request_type=product_search_service.ListProductsInProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -16040,27 +14299,25 @@ def test_list_products_in_product_set_rest_bad_request( client.list_products_in_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsInProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsInProductSetRequest, + dict, +]) def test_list_products_in_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -16068,48 +14325,35 @@ def test_list_products_in_product_set_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products_in_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_products_in_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_products_in_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_list_products_in_product_set_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_products_in_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_in_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_in_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_products_in_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductsInProductSetRequest.pb( - product_search_service.ListProductsInProductSetRequest() - ) + pb_message = product_search_service.ListProductsInProductSetRequest.pb(product_search_service.ListProductsInProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16120,53 +14364,39 @@ def test_list_products_in_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductsInProductSetResponse.to_json( - product_search_service.ListProductsInProductSetResponse() - ) + return_value = product_search_service.ListProductsInProductSetResponse.to_json(product_search_service.ListProductsInProductSetResponse()) req.return_value.content = return_value request = product_search_service.ListProductsInProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductsInProductSetResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductsInProductSetResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductsInProductSetResponse(), metadata - client.list_products_in_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_products_in_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_import_product_sets_rest_bad_request( - request_type=product_search_service.ImportProductSetsRequest, -): +def test_import_product_sets_rest_bad_request(request_type=product_search_service.ImportProductSetsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -16175,32 +14405,30 @@ def test_import_product_sets_rest_bad_request( client.import_product_sets(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ImportProductSetsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ImportProductSetsRequest, + dict, +]) def test_import_product_sets_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.import_product_sets(request) @@ -16213,32 +14441,20 @@ def test_import_product_sets_rest_call_success(request_type): def test_import_product_sets_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_import_product_sets" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_import_product_sets_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_import_product_sets" - ) as pre: + 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.ProductSearchRestInterceptor, "post_import_product_sets") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_import_product_sets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_import_product_sets") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ImportProductSetsRequest.pb( - product_search_service.ImportProductSetsRequest() - ) + pb_message = product_search_service.ImportProductSetsRequest.pb(product_search_service.ImportProductSetsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16253,7 +14469,7 @@ def test_import_product_sets_rest_interceptors(null_interceptor): req.return_value.content = return_value request = product_search_service.ImportProductSetsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -16261,36 +14477,27 @@ def test_import_product_sets_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.import_product_sets( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.import_product_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_purge_products_rest_bad_request( - request_type=product_search_service.PurgeProductsRequest, -): +def test_purge_products_rest_bad_request(request_type=product_search_service.PurgeProductsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -16299,32 +14506,30 @@ def test_purge_products_rest_bad_request( client.purge_products(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.PurgeProductsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.PurgeProductsRequest, + dict, +]) def test_purge_products_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.purge_products(request) @@ -16337,31 +14542,20 @@ def test_purge_products_rest_call_success(request_type): def test_purge_products_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_purge_products" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_purge_products_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_purge_products" - ) as pre: + 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.ProductSearchRestInterceptor, "post_purge_products") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_purge_products_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_purge_products") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.PurgeProductsRequest.pb( - product_search_service.PurgeProductsRequest() - ) + pb_message = product_search_service.PurgeProductsRequest.pb(product_search_service.PurgeProductsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16376,7 +14570,7 @@ def test_purge_products_rest_interceptors(null_interceptor): req.return_value.content = return_value request = product_search_service.PurgeProductsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -16384,38 +14578,26 @@ def test_purge_products_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.purge_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.purge_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_operation_rest_bad_request( - request_type=operations_pb2.GetOperationRequest, -): +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/operations/sample2"}, request - ) + request = json_format.ParseDict({'name': 'projects/sample1/operations/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -16424,23 +14606,20 @@ def test_get_operation_rest_bad_request( client.get_operation(request) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) def test_get_operation_rest(request_type): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/operations/sample2"} + request_init = {'name': 'projects/sample1/operations/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + with mock.patch.object(Session, 'request') as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation() @@ -16448,7 +14627,7 @@ def test_get_operation_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -16458,10 +14637,10 @@ def test_get_operation_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) - def test_initialize_client_w_rest(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -16476,8 +14655,8 @@ def test_create_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: client.create_product_set(request=None) # Establish that the underlying stub method was called. @@ -16498,8 +14677,8 @@ def test_list_product_sets_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: client.list_product_sets(request=None) # Establish that the underlying stub method was called. @@ -16519,7 +14698,9 @@ def test_get_product_set_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: client.get_product_set(request=None) # Establish that the underlying stub method was called. @@ -16540,8 +14721,8 @@ def test_update_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: client.update_product_set(request=None) # Establish that the underlying stub method was called. @@ -16562,8 +14743,8 @@ def test_delete_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: client.delete_product_set(request=None) # Establish that the underlying stub method was called. @@ -16583,7 +14764,9 @@ def test_create_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: client.create_product(request=None) # Establish that the underlying stub method was called. @@ -16603,7 +14786,9 @@ def test_list_products_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: client.list_products(request=None) # Establish that the underlying stub method was called. @@ -16623,7 +14808,9 @@ def test_get_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: client.get_product(request=None) # Establish that the underlying stub method was called. @@ -16643,7 +14830,9 @@ def test_update_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: client.update_product(request=None) # Establish that the underlying stub method was called. @@ -16663,7 +14852,9 @@ def test_delete_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: client.delete_product(request=None) # Establish that the underlying stub method was called. @@ -16684,8 +14875,8 @@ def test_create_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: client.create_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16706,8 +14897,8 @@ def test_delete_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: client.delete_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16728,8 +14919,8 @@ def test_list_reference_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: client.list_reference_images(request=None) # Establish that the underlying stub method was called. @@ -16750,8 +14941,8 @@ def test_get_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: client.get_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16772,8 +14963,8 @@ def test_add_product_to_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: client.add_product_to_product_set(request=None) # Establish that the underlying stub method was called. @@ -16794,8 +14985,8 @@ def test_remove_product_from_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: client.remove_product_from_product_set(request=None) # Establish that the underlying stub method was called. @@ -16816,8 +15007,8 @@ def test_list_products_in_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: client.list_products_in_product_set(request=None) # Establish that the underlying stub method was called. @@ -16838,8 +15029,8 @@ def test_import_product_sets_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: client.import_product_sets(request=None) # Establish that the underlying stub method was called. @@ -16859,7 +15050,9 @@ def test_purge_products_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: client.purge_products(request=None) # Establish that the underlying stub method was called. @@ -16880,13 +15073,12 @@ def test_product_search_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ProductSearchClient( @@ -16897,21 +15089,18 @@ def test_transport_grpc_default(): transports.ProductSearchGrpcTransport, ) - def test_product_search_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProductSearchTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_product_search_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport.__init__') as Transport: Transport.return_value = None transport = transports.ProductSearchTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -16920,26 +15109,26 @@ def test_product_search_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "create_product_set", - "list_product_sets", - "get_product_set", - "update_product_set", - "delete_product_set", - "create_product", - "list_products", - "get_product", - "update_product", - "delete_product", - "create_reference_image", - "delete_reference_image", - "list_reference_images", - "get_reference_image", - "add_product_to_product_set", - "remove_product_from_product_set", - "list_products_in_product_set", - "import_product_sets", - "purge_products", - "get_operation", + 'create_product_set', + 'list_product_sets', + 'get_product_set', + 'update_product_set', + 'delete_product_set', + 'create_product', + 'list_products', + 'get_product', + 'update_product', + 'delete_product', + 'create_reference_image', + 'delete_reference_image', + 'list_reference_images', + 'get_reference_image', + 'add_product_to_product_set', + 'remove_product_from_product_set', + 'list_products_in_product_set', + 'import_product_sets', + 'purge_products', + 'get_operation', ) for method in methods: with pytest.raises(NotImplementedError): @@ -16955,7 +15144,7 @@ def test_product_search_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -16964,33 +15153,26 @@ def test_product_search_base_transport(): def test_product_search_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.vision_v1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_product_search_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.vision_v1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport() @@ -16999,15 +15181,15 @@ def test_product_search_base_transport_with_adc(): def test_product_search_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ProductSearchClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -17022,15 +15204,12 @@ def test_product_search_auth_adc(): def test_product_search_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -17044,38 +15223,39 @@ def test_product_search_transport_auth_adc(transport_class): ], ) def test_product_search_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ProductSearchGrpcTransport, grpc_helpers), - (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_product_search_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -17083,9 +15263,9 @@ def test_product_search_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -17096,14 +15276,10 @@ def test_product_search_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -17112,7 +15288,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -17133,77 +15309,61 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_product_search_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.ProductSearchRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ProductSearchRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_product_search_host_no_port(transport_name): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_product_search_host_with_port(transport_name): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_product_search_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -17272,10 +15432,8 @@ def test_product_search_client_transport_session_collision(transport_name): session1 = client1.transport.purge_products._session session2 = client2.transport.purge_products._session assert session1 != session2 - - def test_product_search_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ProductSearchGrpcTransport( @@ -17288,7 +15446,7 @@ def test_product_search_grpc_transport_channel(): def test_product_search_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ProductSearchGrpcAsyncIOTransport( @@ -17303,20 +15461,12 @@ def test_product_search_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_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: +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_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 @@ -17325,7 +15475,7 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -17355,23 +15505,17 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport # 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.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_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: + 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() @@ -17402,7 +15546,7 @@ def test_product_search_transport_channel_mtls_with_adc(transport_class): def test_product_search_grpc_lro_client(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -17419,7 +15563,7 @@ def test_product_search_grpc_lro_client(): def test_product_search_grpc_lro_async_client(): client = ProductSearchAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -17437,11 +15581,7 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + expected = "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) actual = ProductSearchClient.product_path(project, location, product) assert expected == actual @@ -17458,18 +15598,11 @@ def test_parse_product_path(): actual = ProductSearchClient.parse_product_path(path) assert expected == actual - def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) actual = ProductSearchClient.product_set_path(project, location, product_set) assert expected == actual @@ -17486,21 +15619,13 @@ def test_parse_product_set_path(): actual = ProductSearchClient.parse_product_set_path(path) assert expected == actual - def test_reference_image_path(): project = "squid" location = "clam" product = "whelk" reference_image = "octopus" - expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( - project=project, - location=location, - product=product, - reference_image=reference_image, - ) - actual = ProductSearchClient.reference_image_path( - project, location, product, reference_image - ) + expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format(project=project, location=location, product=product, reference_image=reference_image, ) + actual = ProductSearchClient.reference_image_path(project, location, product, reference_image) assert expected == actual @@ -17517,12 +15642,9 @@ def test_parse_reference_image_path(): actual = ProductSearchClient.parse_reference_image_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ProductSearchClient.common_billing_account_path(billing_account) assert expected == actual @@ -17537,12 +15659,9 @@ def test_parse_common_billing_account_path(): actual = ProductSearchClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ProductSearchClient.common_folder_path(folder) assert expected == actual @@ -17557,12 +15676,9 @@ def test_parse_common_folder_path(): actual = ProductSearchClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ProductSearchClient.common_organization_path(organization) assert expected == actual @@ -17577,12 +15693,9 @@ def test_parse_common_organization_path(): actual = ProductSearchClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ProductSearchClient.common_project_path(project) assert expected == actual @@ -17597,14 +15710,10 @@ def test_parse_common_project_path(): actual = ProductSearchClient.parse_common_project_path(path) assert expected == actual - def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ProductSearchClient.common_location_path(project, location) assert expected == actual @@ -17624,18 +15733,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ProductSearchTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ProductSearchTransport, '_prep_wrapped_messages') as prep: client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ProductSearchTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ProductSearchTransport, '_prep_wrapped_messages') as prep: transport_class = ProductSearchClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -17646,8 +15751,7 @@ def test_client_with_default_client_info(): def test_get_operation(transport: str = "grpc"): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -17666,13 +15770,10 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) - - @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, + credentials=async_anonymous_credentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -17694,7 +15795,6 @@ async def test_get_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) - def test_get_operation_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17717,12 +15817,7 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=locations", - ) in kw["metadata"] - - + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProductSearchAsyncClient( @@ -17747,11 +15842,7 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=locations", - ) in kw["metadata"] - + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] def test_get_operation_from_dict(): client = ProductSearchClient( @@ -17768,8 +15859,6 @@ def test_get_operation_from_dict(): } ) call.assert_called() - - @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProductSearchAsyncClient( @@ -17791,11 +15880,10 @@ async def test_get_operation_from_dict_async(): def test_transport_close_grpc(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -17804,11 +15892,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -17816,11 +15903,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -17828,12 +15914,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -17842,14 +15929,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport), - (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -17864,9 +15947,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/__init__.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py index c9ce8ca8bddf..61dd10817106 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,43 +21,45 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p1beta1.services.image_annotator import ImageAnnotatorAsyncClient +from google.cloud.vision_v1p1beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p1beta1.services.image_annotator import transports +from google.cloud.vision_v1p1beta1.types import image_annotator from google.oauth2 import service_account from google.type import latlng_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1p1beta1.services.image_annotator import ( - ImageAnnotatorAsyncClient, - ImageAnnotatorClient, - transports, -) -from google.cloud.vision_v1p1beta1.types import image_annotator CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -73,11 +74,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -85,27 +84,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -116,43 +105,20 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - True, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -166,46 +132,27 @@ def test__read_environment_variables(): ) else: assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ImageAnnotatorClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ImageAnnotatorClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ImageAnnotatorClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -214,9 +161,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ImageAnnotatorClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -224,9 +169,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -238,9 +181,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -252,9 +193,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -266,9 +205,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -283,167 +220,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ImageAnnotatorClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ImageAnnotatorClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ImageAnnotatorClient._get_client_cert_source(None, False) is None - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) - - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ImageAnnotatorClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ImageAnnotatorClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ImageAnnotatorClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ImageAnnotatorClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ImageAnnotatorClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ImageAnnotatorClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, None) - == ImageAnnotatorClient._DEFAULT_UNIVERSE - ) + assert ImageAnnotatorClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageAnnotatorClient._get_universe_domain(None, None) == ImageAnnotatorClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ImageAnnotatorClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -459,8 +312,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -473,20 +325,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -494,68 +340,52 @@ def test_image_annotator_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ImageAnnotatorGrpcTransport, "grpc"), - (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageAnnotatorGrpcTransport, "grpc"), + (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -571,45 +401,30 @@ def test_image_annotator_client_get_transport_class(): assert transport == transports.ImageAnnotatorGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) -def test_image_annotator_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) +def test_image_annotator_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -627,15 +442,13 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -647,7 +460,7 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -667,22 +480,17 @@ def test_image_annotator_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -691,82 +499,48 @@ def test_image_annotator_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_annotator_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_image_annotator_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -785,22 +559,12 @@ def test_image_annotator_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -821,22 +585,15 @@ def test_image_annotator_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -846,31 +603,19 @@ def test_image_annotator_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorAsyncClient)) def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -878,25 +623,18 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -933,24 +671,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -981,24 +718,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1014,28 +750,16 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1045,50 +769,27 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test_image_annotator_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1111,19 +812,11 @@ def test_image_annotator_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1131,40 +824,27 @@ def test_image_annotator_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1173,40 +853,24 @@ def test_image_annotator_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), - ], -) -def test_image_annotator_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), +]) +def test_image_annotator_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1215,14 +879,11 @@ def test_image_annotator_client_client_options_credentials_file( api_audience=None, ) - def test_image_annotator_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ImageAnnotatorClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1237,38 +898,23 @@ def test_image_annotator_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_image_annotator_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_annotator_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1296,9 +942,9 @@ def test_image_annotator_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1309,14 +955,11 @@ def test_image_annotator_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) -def test_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) +def test_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1328,10 +971,11 @@ def test_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateImagesResponse() + call.return_value = image_annotator.BatchAnnotateImagesResponse( + ) response = client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1349,26 +993,25 @@ def test_batch_annotate_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.BatchAnnotateImagesRequest() + request = image_annotator.BatchAnnotateImagesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() - + assert args[0] == image_annotator.BatchAnnotateImagesRequest( + ) def test_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1384,19 +1027,12 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1409,11 +1045,8 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1427,17 +1060,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_images] = mock_rpc request = {} await client.batch_annotate_images(request) @@ -1451,12 +1079,8 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateImagesRequest, -): +async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1468,12 +1092,11 @@ async def test_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) response = await client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1498,18 +1121,14 @@ def test_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1517,11 +1136,7 @@ def test_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val @@ -1535,14 +1150,9 @@ def test_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1551,22 +1161,16 @@ async def test_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1574,14 +1178,9 @@ async def test_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1593,11 +1192,7 @@ async def test_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) @@ -1615,19 +1210,12 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1642,57 +1230,52 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_images_rest_required_fields( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_required_fields(request_type=image_annotator.BatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -1702,24 +1285,24 @@ def test_batch_annotate_images_rest_required_fields( return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_images_rest_flattened(): @@ -1729,7 +1312,7 @@ def test_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() @@ -1738,11 +1321,7 @@ def test_batch_annotate_images_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) mock_args.update(sample_request) @@ -1752,7 +1331,7 @@ def test_batch_annotate_images_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1762,12 +1341,10 @@ def test_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p1beta1/images:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p1beta1/images:annotate" % client.transport._host, args[1]) -def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1778,11 +1355,7 @@ def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) @@ -1824,7 +1397,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ImageAnnotatorClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -1846,7 +1420,6 @@ def test_transport_instance(): client = ImageAnnotatorClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( @@ -1861,23 +1434,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - transports.ImageAnnotatorRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + transports.ImageAnnotatorRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ImageAnnotatorClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1887,7 +1455,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -1902,8 +1471,8 @@ def test_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateImagesResponse() client.batch_annotate_images(request=None) @@ -1924,7 +1493,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -1940,12 +1510,11 @@ async def test_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) await client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -1963,23 +1532,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_batch_annotate_images_rest_bad_request( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -1988,16 +1554,14 @@ def test_batch_annotate_images_rest_bad_request( client.batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) def test_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -2005,9 +1569,10 @@ def test_batch_annotate_images_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateImagesResponse() + return_value = image_annotator.BatchAnnotateImagesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -2016,7 +1581,7 @@ def test_batch_annotate_images_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) @@ -2029,30 +1594,19 @@ def test_batch_annotate_images_rest_call_success(request_type): def test_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateImagesRequest.pb( - image_annotator.BatchAnnotateImagesRequest() - ) + pb_message = image_annotator.BatchAnnotateImagesRequest.pb(image_annotator.BatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2063,39 +1617,28 @@ def test_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateImagesResponse.to_json( - image_annotator.BatchAnnotateImagesResponse() - ) + return_value = image_annotator.BatchAnnotateImagesResponse.to_json(image_annotator.BatchAnnotateImagesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateImagesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateImagesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateImagesResponse(), metadata - client.batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -2110,8 +1653,8 @@ def test_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -2132,21 +1675,18 @@ def test_transport_grpc_default(): transports.ImageAnnotatorGrpcTransport, ) - def test_image_annotator_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_image_annotator_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__') as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2154,7 +1694,9 @@ def test_image_annotator_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ("batch_annotate_images",) + methods = ( + 'batch_annotate_images', + ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -2164,7 +1706,7 @@ def test_image_annotator_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2173,33 +1715,26 @@ def test_image_annotator_base_transport(): def test_image_annotator_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.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_image_annotator_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.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() @@ -2208,15 +1743,15 @@ def test_image_annotator_base_transport_with_adc(): def test_image_annotator_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -2231,15 +1766,12 @@ def test_image_annotator_auth_adc(): def test_image_annotator_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -2253,38 +1785,39 @@ def test_image_annotator_transport_auth_adc(transport_class): ], ) def test_image_annotator_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ImageAnnotatorGrpcTransport, grpc_helpers), - (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_image_annotator_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -2292,9 +1825,9 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -2305,14 +1838,10 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -2321,7 +1850,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -2342,77 +1871,61 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_image_annotator_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.ImageAnnotatorRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ImageAnnotatorRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_no_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_with_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_image_annotator_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2427,10 +1940,8 @@ def test_image_annotator_client_transport_session_collision(transport_name): session1 = client1.transport.batch_annotate_images._session session2 = client2.transport.batch_annotate_images._session assert session1 != session2 - - def test_image_annotator_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcTransport( @@ -2443,7 +1954,7 @@ def test_image_annotator_grpc_transport_channel(): def test_image_annotator_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcAsyncIOTransport( @@ -2458,22 +1969,12 @@ def test_image_annotator_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) def test_image_annotator_transport_channel_mtls_with_client_cert_source( - transport_class, + 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: + 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 @@ -2482,7 +1983,7 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2512,23 +2013,17 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( # 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.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_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: + 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() @@ -2558,9 +2053,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ImageAnnotatorClient.common_billing_account_path(billing_account) assert expected == actual @@ -2575,12 +2068,9 @@ def test_parse_common_billing_account_path(): actual = ImageAnnotatorClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -2595,12 +2085,9 @@ def test_parse_common_folder_path(): actual = ImageAnnotatorClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -2615,12 +2102,9 @@ def test_parse_common_organization_path(): actual = ImageAnnotatorClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -2635,14 +2119,10 @@ def test_parse_common_project_path(): actual = ImageAnnotatorClient.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, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ImageAnnotatorClient.common_location_path(project, location) assert expected == actual @@ -2662,18 +2142,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2684,11 +2160,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -2697,11 +2172,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -2709,11 +2183,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -2721,12 +2194,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -2735,14 +2209,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), - (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2757,9 +2227,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/__init__.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py index 3f12d6920955..f6c483a6dbb6 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py @@ -15,7 +15,6 @@ # import os import re - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -23,53 +22,50 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1p2beta1.services.image_annotator import ImageAnnotatorAsyncClient +from google.cloud.vision_v1p2beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p2beta1.services.image_annotator import transports +from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.type import latlng_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1p2beta1.services.image_annotator import ( - ImageAnnotatorAsyncClient, - ImageAnnotatorClient, - transports, -) -from google.cloud.vision_v1p2beta1.types import image_annotator CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -84,11 +80,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -96,27 +90,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -127,43 +111,20 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - True, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -177,46 +138,27 @@ def test__read_environment_variables(): ) else: assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ImageAnnotatorClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ImageAnnotatorClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ImageAnnotatorClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -225,9 +167,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ImageAnnotatorClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -235,9 +175,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -249,9 +187,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -263,9 +199,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -277,9 +211,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -294,167 +226,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ImageAnnotatorClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ImageAnnotatorClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ImageAnnotatorClient._get_client_cert_source(None, False) is None - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ImageAnnotatorClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ImageAnnotatorClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ImageAnnotatorClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ImageAnnotatorClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ImageAnnotatorClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ImageAnnotatorClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, None) - == ImageAnnotatorClient._DEFAULT_UNIVERSE - ) + assert ImageAnnotatorClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageAnnotatorClient._get_universe_domain(None, None) == ImageAnnotatorClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ImageAnnotatorClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -470,8 +318,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -484,20 +331,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -505,68 +346,52 @@ def test_image_annotator_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ImageAnnotatorGrpcTransport, "grpc"), - (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageAnnotatorGrpcTransport, "grpc"), + (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -582,45 +407,30 @@ def test_image_annotator_client_get_transport_class(): assert transport == transports.ImageAnnotatorGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) -def test_image_annotator_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) +def test_image_annotator_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -638,15 +448,13 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -658,7 +466,7 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -678,22 +486,17 @@ def test_image_annotator_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -702,82 +505,48 @@ def test_image_annotator_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_annotator_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_image_annotator_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -796,22 +565,12 @@ def test_image_annotator_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -832,22 +591,15 @@ def test_image_annotator_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -857,31 +609,19 @@ def test_image_annotator_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorAsyncClient)) def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -889,25 +629,18 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -944,24 +677,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -992,24 +724,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1025,28 +756,16 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1056,50 +775,27 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test_image_annotator_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1122,19 +818,11 @@ def test_image_annotator_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1142,40 +830,27 @@ def test_image_annotator_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1184,40 +859,24 @@ def test_image_annotator_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), - ], -) -def test_image_annotator_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), +]) +def test_image_annotator_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1226,14 +885,11 @@ def test_image_annotator_client_client_options_credentials_file( api_audience=None, ) - def test_image_annotator_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ImageAnnotatorClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1248,38 +904,23 @@ def test_image_annotator_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_image_annotator_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_annotator_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1307,9 +948,9 @@ def test_image_annotator_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1320,14 +961,11 @@ def test_image_annotator_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) -def test_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) +def test_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1339,10 +977,11 @@ def test_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateImagesResponse() + call.return_value = image_annotator.BatchAnnotateImagesResponse( + ) response = client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1360,26 +999,25 @@ def test_batch_annotate_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.BatchAnnotateImagesRequest() + request = image_annotator.BatchAnnotateImagesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() - + assert args[0] == image_annotator.BatchAnnotateImagesRequest( + ) def test_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1395,19 +1033,12 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1420,11 +1051,8 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1438,17 +1066,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_images] = mock_rpc request = {} await client.batch_annotate_images(request) @@ -1462,12 +1085,8 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateImagesRequest, -): +async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1479,12 +1098,11 @@ async def test_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) response = await client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1509,18 +1127,14 @@ def test_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1528,11 +1142,7 @@ def test_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val @@ -1546,14 +1156,9 @@ def test_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1562,22 +1167,16 @@ async def test_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1585,14 +1184,9 @@ async def test_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1604,22 +1198,15 @@ async def test_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) -def test_async_batch_annotate_files(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) +def test_async_batch_annotate_files(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1631,10 +1218,10 @@ def test_async_batch_annotate_files(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.async_batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -1652,26 +1239,25 @@ def test_async_batch_annotate_files_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.AsyncBatchAnnotateFilesRequest() + request = image_annotator.AsyncBatchAnnotateFilesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.async_batch_annotate_files(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() - + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest( + ) def test_async_batch_annotate_files_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1687,19 +1273,12 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -1717,11 +1296,8 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1735,17 +1311,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.async_batch_annotate_files - in client._client._transport._wrapped_methods - ) + assert client._client._transport.async_batch_annotate_files in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.async_batch_annotate_files - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.async_batch_annotate_files] = mock_rpc request = {} await client.async_batch_annotate_files(request) @@ -1764,12 +1335,8 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1781,11 +1348,11 @@ async def test_async_batch_annotate_files_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.async_batch_annotate_files(request) @@ -1811,20 +1378,14 @@ def test_async_batch_annotate_files_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1832,13 +1393,7 @@ def test_async_batch_annotate_files_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val @@ -1852,16 +1407,9 @@ def test_async_batch_annotate_files_flattened_error(): with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1870,24 +1418,18 @@ async def test_async_batch_annotate_files_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1895,16 +1437,9 @@ async def test_async_batch_annotate_files_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1916,13 +1451,7 @@ async def test_async_batch_annotate_files_flattened_error_async(): with pytest.raises(ValueError): await client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -1940,19 +1469,12 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1967,57 +1489,52 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_images_rest_required_fields( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_required_fields(request_type=image_annotator.BatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2027,24 +1544,24 @@ def test_batch_annotate_images_rest_required_fields( return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_images_rest_flattened(): @@ -2054,7 +1571,7 @@ def test_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() @@ -2063,11 +1580,7 @@ def test_batch_annotate_images_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) mock_args.update(sample_request) @@ -2077,7 +1590,7 @@ def test_batch_annotate_images_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2087,12 +1600,10 @@ def test_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p2beta1/images:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p2beta1/images:annotate" % client.transport._host, args[1]) -def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2103,11 +1614,7 @@ def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) @@ -2125,19 +1632,12 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -2156,81 +1656,76 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_async_batch_annotate_files_rest_required_fields( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_required_fields(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_async_batch_annotate_files_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.async_batch_annotate_files._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_async_batch_annotate_files_rest_flattened(): @@ -2240,22 +1735,16 @@ def test_async_batch_annotate_files_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method sample_request = {} # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) mock_args.update(sample_request) @@ -2263,7 +1752,7 @@ def test_async_batch_annotate_files_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2273,12 +1762,10 @@ def test_async_batch_annotate_files_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p2beta1/files:asyncBatchAnnotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p2beta1/files:asyncBatchAnnotate" % client.transport._host, args[1]) -def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest"): +def test_async_batch_annotate_files_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2289,13 +1776,7 @@ def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -2337,7 +1818,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ImageAnnotatorClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -2359,7 +1841,6 @@ def test_transport_instance(): client = ImageAnnotatorClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( @@ -2374,23 +1855,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - transports.ImageAnnotatorRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + transports.ImageAnnotatorRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ImageAnnotatorClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2400,7 +1876,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -2415,8 +1892,8 @@ def test_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateImagesResponse() client.batch_annotate_images(request=None) @@ -2438,9 +1915,9 @@ def test_async_batch_annotate_files_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -2460,7 +1937,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -2476,12 +1954,11 @@ async def test_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) await client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -2503,11 +1980,11 @@ async def test_async_batch_annotate_files_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.async_batch_annotate_files(request=None) @@ -2526,23 +2003,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_batch_annotate_images_rest_bad_request( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -2551,16 +2025,14 @@ def test_batch_annotate_images_rest_bad_request( client.batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) def test_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -2568,9 +2040,10 @@ def test_batch_annotate_images_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateImagesResponse() + return_value = image_annotator.BatchAnnotateImagesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -2579,7 +2052,7 @@ def test_batch_annotate_images_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) @@ -2592,30 +2065,19 @@ def test_batch_annotate_images_rest_call_success(request_type): def test_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateImagesRequest.pb( - image_annotator.BatchAnnotateImagesRequest() - ) + pb_message = image_annotator.BatchAnnotateImagesRequest.pb(image_annotator.BatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2626,53 +2088,39 @@ def test_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateImagesResponse.to_json( - image_annotator.BatchAnnotateImagesResponse() - ) + return_value = image_annotator.BatchAnnotateImagesResponse.to_json(image_annotator.BatchAnnotateImagesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateImagesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateImagesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateImagesResponse(), metadata - client.batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_async_batch_annotate_files_rest_bad_request( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -2681,16 +2129,14 @@ def test_async_batch_annotate_files_rest_bad_request( client.async_batch_annotate_files(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) def test_async_batch_annotate_files_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -2698,15 +2144,15 @@ def test_async_batch_annotate_files_rest_call_success(request_type): 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) @@ -2719,32 +2165,20 @@ def test_async_batch_annotate_files_rest_call_success(request_type): def test_async_batch_annotate_files_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_async_batch_annotate_files_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files" - ) as pre: + 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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb( - image_annotator.AsyncBatchAnnotateFilesRequest() - ) + pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb(image_annotator.AsyncBatchAnnotateFilesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2759,7 +2193,7 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): req.return_value.content = return_value request = image_annotator.AsyncBatchAnnotateFilesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -2767,22 +2201,16 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.async_batch_annotate_files( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.async_batch_annotate_files(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -2797,8 +2225,8 @@ def test_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -2819,8 +2247,8 @@ def test_async_batch_annotate_files_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -2841,13 +2269,12 @@ def test_image_annotator_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ImageAnnotatorClient( @@ -2858,21 +2285,18 @@ def test_transport_grpc_default(): transports.ImageAnnotatorGrpcTransport, ) - def test_image_annotator_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_image_annotator_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__') as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2881,8 +2305,8 @@ def test_image_annotator_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "batch_annotate_images", - "async_batch_annotate_files", + 'batch_annotate_images', + 'async_batch_annotate_files', ) for method in methods: with pytest.raises(NotImplementedError): @@ -2898,7 +2322,7 @@ def test_image_annotator_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2907,33 +2331,26 @@ def test_image_annotator_base_transport(): def test_image_annotator_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.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_image_annotator_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.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() @@ -2942,15 +2359,15 @@ def test_image_annotator_base_transport_with_adc(): def test_image_annotator_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -2965,15 +2382,12 @@ def test_image_annotator_auth_adc(): def test_image_annotator_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -2987,38 +2401,39 @@ def test_image_annotator_transport_auth_adc(transport_class): ], ) def test_image_annotator_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ImageAnnotatorGrpcTransport, grpc_helpers), - (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_image_annotator_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -3026,9 +2441,9 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -3039,14 +2454,10 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -3055,7 +2466,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -3076,77 +2487,61 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_image_annotator_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.ImageAnnotatorRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ImageAnnotatorRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_no_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_with_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_image_annotator_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3164,10 +2559,8 @@ def test_image_annotator_client_transport_session_collision(transport_name): session1 = client1.transport.async_batch_annotate_files._session session2 = client2.transport.async_batch_annotate_files._session assert session1 != session2 - - def test_image_annotator_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcTransport( @@ -3180,7 +2573,7 @@ def test_image_annotator_grpc_transport_channel(): def test_image_annotator_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcAsyncIOTransport( @@ -3195,22 +2588,12 @@ def test_image_annotator_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) def test_image_annotator_transport_channel_mtls_with_client_cert_source( - transport_class, + 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: + 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 @@ -3219,7 +2602,7 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3249,23 +2632,17 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( # 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.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_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: + 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() @@ -3296,7 +2673,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -3313,7 +2690,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -3329,9 +2706,7 @@ def test_image_annotator_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ImageAnnotatorClient.common_billing_account_path(billing_account) assert expected == actual @@ -3346,12 +2721,9 @@ def test_parse_common_billing_account_path(): actual = ImageAnnotatorClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -3366,12 +2738,9 @@ def test_parse_common_folder_path(): actual = ImageAnnotatorClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -3386,12 +2755,9 @@ def test_parse_common_organization_path(): actual = ImageAnnotatorClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -3406,14 +2772,10 @@ def test_parse_common_project_path(): actual = ImageAnnotatorClient.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, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ImageAnnotatorClient.common_location_path(project, location) assert expected == actual @@ -3433,18 +2795,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3455,11 +2813,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -3468,11 +2825,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -3480,11 +2836,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -3492,12 +2847,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -3506,14 +2862,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), - (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3528,9 +2880,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/__init__.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py index dbb2d9cb8abb..eb8fba26dcae 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,57 +21,52 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1p3beta1.services.image_annotator import ImageAnnotatorAsyncClient +from google.cloud.vision_v1p3beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p3beta1.services.image_annotator import transports +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import image_annotator +from google.cloud.vision_v1p3beta1.types import product_search +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.type import latlng_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1p3beta1.services.image_annotator import ( - ImageAnnotatorAsyncClient, - ImageAnnotatorClient, - transports, -) -from google.cloud.vision_v1p3beta1.types import ( - geometry, - image_annotator, - product_search, -) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -87,11 +81,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -99,27 +91,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -130,43 +112,20 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - True, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -180,46 +139,27 @@ def test__read_environment_variables(): ) else: assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ImageAnnotatorClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ImageAnnotatorClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ImageAnnotatorClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -228,9 +168,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ImageAnnotatorClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -238,9 +176,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -252,9 +188,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -266,9 +200,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -280,9 +212,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -297,167 +227,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ImageAnnotatorClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ImageAnnotatorClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ImageAnnotatorClient._get_client_cert_source(None, False) is None - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ImageAnnotatorClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ImageAnnotatorClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ImageAnnotatorClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ImageAnnotatorClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ImageAnnotatorClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ImageAnnotatorClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, None) - == ImageAnnotatorClient._DEFAULT_UNIVERSE - ) + assert ImageAnnotatorClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageAnnotatorClient._get_universe_domain(None, None) == ImageAnnotatorClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ImageAnnotatorClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -473,8 +319,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -487,20 +332,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -508,68 +347,52 @@ def test_image_annotator_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ImageAnnotatorGrpcTransport, "grpc"), - (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageAnnotatorGrpcTransport, "grpc"), + (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -585,45 +408,30 @@ def test_image_annotator_client_get_transport_class(): assert transport == transports.ImageAnnotatorGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) -def test_image_annotator_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) +def test_image_annotator_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -641,15 +449,13 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -661,7 +467,7 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -681,22 +487,17 @@ def test_image_annotator_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -705,82 +506,48 @@ def test_image_annotator_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_annotator_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_image_annotator_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -799,22 +566,12 @@ def test_image_annotator_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -835,22 +592,15 @@ def test_image_annotator_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -860,31 +610,19 @@ def test_image_annotator_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorAsyncClient)) def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -892,25 +630,18 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -947,24 +678,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -995,24 +725,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1028,28 +757,16 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1059,50 +776,27 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test_image_annotator_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1125,19 +819,11 @@ def test_image_annotator_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1145,40 +831,27 @@ def test_image_annotator_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1187,40 +860,24 @@ def test_image_annotator_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), - ], -) -def test_image_annotator_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), +]) +def test_image_annotator_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1229,14 +886,11 @@ def test_image_annotator_client_client_options_credentials_file( api_audience=None, ) - def test_image_annotator_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ImageAnnotatorClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1251,38 +905,23 @@ def test_image_annotator_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_image_annotator_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_annotator_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1310,9 +949,9 @@ def test_image_annotator_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1323,14 +962,11 @@ def test_image_annotator_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) -def test_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) +def test_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1342,10 +978,11 @@ def test_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateImagesResponse() + call.return_value = image_annotator.BatchAnnotateImagesResponse( + ) response = client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1363,26 +1000,25 @@ def test_batch_annotate_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.BatchAnnotateImagesRequest() + request = image_annotator.BatchAnnotateImagesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() - + assert args[0] == image_annotator.BatchAnnotateImagesRequest( + ) def test_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1398,19 +1034,12 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1423,11 +1052,8 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1441,17 +1067,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_images] = mock_rpc request = {} await client.batch_annotate_images(request) @@ -1465,12 +1086,8 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateImagesRequest, -): +async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1482,12 +1099,11 @@ async def test_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) response = await client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1512,18 +1128,14 @@ def test_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1531,11 +1143,7 @@ def test_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val @@ -1549,14 +1157,9 @@ def test_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1565,22 +1168,16 @@ async def test_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1588,14 +1185,9 @@ async def test_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1607,22 +1199,15 @@ async def test_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) -def test_async_batch_annotate_files(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) +def test_async_batch_annotate_files(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1634,10 +1219,10 @@ def test_async_batch_annotate_files(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.async_batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -1655,26 +1240,25 @@ def test_async_batch_annotate_files_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.AsyncBatchAnnotateFilesRequest() + request = image_annotator.AsyncBatchAnnotateFilesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.async_batch_annotate_files(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() - + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest( + ) def test_async_batch_annotate_files_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1690,19 +1274,12 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -1720,11 +1297,8 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1738,17 +1312,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.async_batch_annotate_files - in client._client._transport._wrapped_methods - ) + assert client._client._transport.async_batch_annotate_files in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.async_batch_annotate_files - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.async_batch_annotate_files] = mock_rpc request = {} await client.async_batch_annotate_files(request) @@ -1767,12 +1336,8 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1784,11 +1349,11 @@ async def test_async_batch_annotate_files_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.async_batch_annotate_files(request) @@ -1814,20 +1379,14 @@ def test_async_batch_annotate_files_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1835,13 +1394,7 @@ def test_async_batch_annotate_files_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val @@ -1855,16 +1408,9 @@ def test_async_batch_annotate_files_flattened_error(): with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1873,24 +1419,18 @@ async def test_async_batch_annotate_files_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1898,16 +1438,9 @@ async def test_async_batch_annotate_files_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1919,13 +1452,7 @@ async def test_async_batch_annotate_files_flattened_error_async(): with pytest.raises(ValueError): await client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -1943,19 +1470,12 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1970,57 +1490,52 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_images_rest_required_fields( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_required_fields(request_type=image_annotator.BatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2030,24 +1545,24 @@ def test_batch_annotate_images_rest_required_fields( return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_images_rest_flattened(): @@ -2057,7 +1572,7 @@ def test_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() @@ -2066,11 +1581,7 @@ def test_batch_annotate_images_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) mock_args.update(sample_request) @@ -2080,7 +1591,7 @@ def test_batch_annotate_images_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2090,12 +1601,10 @@ def test_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/images:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p3beta1/images:annotate" % client.transport._host, args[1]) -def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2106,11 +1615,7 @@ def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) @@ -2128,19 +1633,12 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -2159,81 +1657,76 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_async_batch_annotate_files_rest_required_fields( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_required_fields(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_async_batch_annotate_files_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.async_batch_annotate_files._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_async_batch_annotate_files_rest_flattened(): @@ -2243,22 +1736,16 @@ def test_async_batch_annotate_files_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method sample_request = {} # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) mock_args.update(sample_request) @@ -2266,7 +1753,7 @@ def test_async_batch_annotate_files_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2276,12 +1763,10 @@ def test_async_batch_annotate_files_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/files:asyncBatchAnnotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p3beta1/files:asyncBatchAnnotate" % client.transport._host, args[1]) -def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest"): +def test_async_batch_annotate_files_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2292,13 +1777,7 @@ def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -2340,7 +1819,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ImageAnnotatorClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -2362,7 +1842,6 @@ def test_transport_instance(): client = ImageAnnotatorClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( @@ -2377,23 +1856,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - transports.ImageAnnotatorRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + transports.ImageAnnotatorRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ImageAnnotatorClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2403,7 +1877,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -2418,8 +1893,8 @@ def test_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateImagesResponse() client.batch_annotate_images(request=None) @@ -2441,9 +1916,9 @@ def test_async_batch_annotate_files_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -2463,7 +1938,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -2479,12 +1955,11 @@ async def test_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) await client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -2506,11 +1981,11 @@ async def test_async_batch_annotate_files_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.async_batch_annotate_files(request=None) @@ -2529,23 +2004,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_batch_annotate_images_rest_bad_request( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -2554,16 +2026,14 @@ def test_batch_annotate_images_rest_bad_request( client.batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) def test_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -2571,9 +2041,10 @@ def test_batch_annotate_images_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateImagesResponse() + return_value = image_annotator.BatchAnnotateImagesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -2582,7 +2053,7 @@ def test_batch_annotate_images_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) @@ -2595,30 +2066,19 @@ def test_batch_annotate_images_rest_call_success(request_type): def test_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateImagesRequest.pb( - image_annotator.BatchAnnotateImagesRequest() - ) + pb_message = image_annotator.BatchAnnotateImagesRequest.pb(image_annotator.BatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2629,53 +2089,39 @@ def test_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateImagesResponse.to_json( - image_annotator.BatchAnnotateImagesResponse() - ) + return_value = image_annotator.BatchAnnotateImagesResponse.to_json(image_annotator.BatchAnnotateImagesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateImagesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateImagesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateImagesResponse(), metadata - client.batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_async_batch_annotate_files_rest_bad_request( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -2684,16 +2130,14 @@ def test_async_batch_annotate_files_rest_bad_request( client.async_batch_annotate_files(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) def test_async_batch_annotate_files_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -2701,15 +2145,15 @@ def test_async_batch_annotate_files_rest_call_success(request_type): 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) @@ -2722,32 +2166,20 @@ def test_async_batch_annotate_files_rest_call_success(request_type): def test_async_batch_annotate_files_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_async_batch_annotate_files_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files" - ) as pre: + 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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb( - image_annotator.AsyncBatchAnnotateFilesRequest() - ) + pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb(image_annotator.AsyncBatchAnnotateFilesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2762,7 +2194,7 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): req.return_value.content = return_value request = image_annotator.AsyncBatchAnnotateFilesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -2770,22 +2202,16 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.async_batch_annotate_files( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.async_batch_annotate_files(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -2800,8 +2226,8 @@ def test_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -2822,8 +2248,8 @@ def test_async_batch_annotate_files_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -2844,13 +2270,12 @@ def test_image_annotator_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ImageAnnotatorClient( @@ -2861,21 +2286,18 @@ def test_transport_grpc_default(): transports.ImageAnnotatorGrpcTransport, ) - def test_image_annotator_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_image_annotator_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__') as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2884,8 +2306,8 @@ def test_image_annotator_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "batch_annotate_images", - "async_batch_annotate_files", + 'batch_annotate_images', + 'async_batch_annotate_files', ) for method in methods: with pytest.raises(NotImplementedError): @@ -2901,7 +2323,7 @@ def test_image_annotator_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2910,33 +2332,26 @@ def test_image_annotator_base_transport(): def test_image_annotator_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.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_image_annotator_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.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() @@ -2945,15 +2360,15 @@ def test_image_annotator_base_transport_with_adc(): def test_image_annotator_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -2968,15 +2383,12 @@ def test_image_annotator_auth_adc(): def test_image_annotator_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -2990,38 +2402,39 @@ def test_image_annotator_transport_auth_adc(transport_class): ], ) def test_image_annotator_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ImageAnnotatorGrpcTransport, grpc_helpers), - (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_image_annotator_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -3029,9 +2442,9 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -3042,14 +2455,10 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -3058,7 +2467,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -3079,77 +2488,61 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_image_annotator_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.ImageAnnotatorRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ImageAnnotatorRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_no_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_with_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_image_annotator_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3167,10 +2560,8 @@ def test_image_annotator_client_transport_session_collision(transport_name): session1 = client1.transport.async_batch_annotate_files._session session2 = client2.transport.async_batch_annotate_files._session assert session1 != session2 - - def test_image_annotator_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcTransport( @@ -3183,7 +2574,7 @@ def test_image_annotator_grpc_transport_channel(): def test_image_annotator_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcAsyncIOTransport( @@ -3198,22 +2589,12 @@ def test_image_annotator_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) def test_image_annotator_transport_channel_mtls_with_client_cert_source( - transport_class, + 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: + 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 @@ -3222,7 +2603,7 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3252,23 +2633,17 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( # 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.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_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: + 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() @@ -3299,7 +2674,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -3316,7 +2691,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -3334,11 +2709,7 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + expected = "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) actual = ImageAnnotatorClient.product_path(project, location, product) assert expected == actual @@ -3355,18 +2726,11 @@ def test_parse_product_path(): actual = ImageAnnotatorClient.parse_product_path(path) assert expected == actual - def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) actual = ImageAnnotatorClient.product_set_path(project, location, product_set) assert expected == actual @@ -3383,12 +2747,9 @@ def test_parse_product_set_path(): actual = ImageAnnotatorClient.parse_product_set_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ImageAnnotatorClient.common_billing_account_path(billing_account) assert expected == actual @@ -3403,12 +2764,9 @@ def test_parse_common_billing_account_path(): actual = ImageAnnotatorClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -3423,12 +2781,9 @@ def test_parse_common_folder_path(): actual = ImageAnnotatorClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -3443,12 +2798,9 @@ def test_parse_common_organization_path(): actual = ImageAnnotatorClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -3463,14 +2815,10 @@ def test_parse_common_project_path(): actual = ImageAnnotatorClient.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, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ImageAnnotatorClient.common_location_path(project, location) assert expected == actual @@ -3490,18 +2838,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3512,11 +2856,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -3525,11 +2868,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -3537,11 +2879,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -3549,12 +2890,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -3563,14 +2905,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), - (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3585,9 +2923,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_product_search.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_product_search.py index a5f93c48545b..2a23346a0f07 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_product_search.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p3beta1/test_product_search.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,57 +21,55 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1p3beta1.services.product_search import ProductSearchAsyncClient +from google.cloud.vision_v1p3beta1.services.product_search import ProductSearchClient +from google.cloud.vision_v1p3beta1.services.product_search import pagers +from google.cloud.vision_v1p3beta1.services.product_search import transports +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1p3beta1.services.product_search import ( - ProductSearchAsyncClient, - ProductSearchClient, - pagers, - transports, -) -from google.cloud.vision_v1p3beta1.types import geometry, product_search_service CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -87,11 +84,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -99,27 +94,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -130,26 +115,11 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ProductSearchClient._get_default_mtls_endpoint(None) is None - assert ( - ProductSearchClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ProductSearchClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ProductSearchClient._read_environment_variables() == (False, "auto", None) @@ -158,11 +128,7 @@ def test__read_environment_variables(): assert ProductSearchClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -176,46 +142,27 @@ def test__read_environment_variables(): ) else: assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ProductSearchClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ProductSearchClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ProductSearchClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -224,9 +171,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ProductSearchClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -234,9 +179,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ProductSearchClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -248,9 +191,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -262,9 +203,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -276,9 +215,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -293,167 +230,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ProductSearchClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ProductSearchClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ProductSearchClient._get_client_cert_source(None, False) is None - assert ( - ProductSearchClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ProductSearchClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) - - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ProductSearchClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ProductSearchClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ProductSearchClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ProductSearchClient._DEFAULT_UNIVERSE - default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ProductSearchClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "always") - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ProductSearchClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "always") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ProductSearchClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ProductSearchClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ProductSearchClient._get_universe_domain(None, None) - == ProductSearchClient._DEFAULT_UNIVERSE - ) + assert ProductSearchClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProductSearchClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProductSearchClient._get_universe_domain(None, None) == ProductSearchClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ProductSearchClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -469,8 +322,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -483,20 +335,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ProductSearchClient, "grpc"), - (ProductSearchAsyncClient, "grpc_asyncio"), - (ProductSearchClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductSearchClient, "grpc"), + (ProductSearchAsyncClient, "grpc_asyncio"), + (ProductSearchClient, "rest"), +]) def test_product_search_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -504,68 +350,52 @@ def test_product_search_client_from_service_account_info(client_class, transport assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ProductSearchGrpcTransport, "grpc"), - (transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProductSearchRestTransport, "rest"), - ], -) -def test_product_search_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductSearchGrpcTransport, "grpc"), + (transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProductSearchRestTransport, "rest"), +]) +def test_product_search_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ProductSearchClient, "grpc"), - (ProductSearchAsyncClient, "grpc_asyncio"), - (ProductSearchClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductSearchClient, "grpc"), + (ProductSearchAsyncClient, "grpc_asyncio"), + (ProductSearchClient, "rest"), +]) def test_product_search_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -581,45 +411,30 @@ def test_product_search_client_get_transport_class(): assert transport == transports.ProductSearchGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), - ], -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) -def test_product_search_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) +def test_product_search_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ProductSearchClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + with mock.patch.object(ProductSearchClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -637,15 +452,13 @@ def test_product_search_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -657,7 +470,7 @@ def test_product_search_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -677,22 +490,17 @@ def test_product_search_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -701,82 +509,48 @@ def test_product_search_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "true"), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "true"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "false"), +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_search_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_product_search_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -795,22 +569,12 @@ def test_product_search_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -831,22 +595,15 @@ def test_product_search_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -856,31 +613,19 @@ def test_product_search_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ProductSearchClient, ProductSearchAsyncClient] -) -@mock.patch.object( - ProductSearchClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ProductSearchAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ProductSearchClient, ProductSearchAsyncClient +]) +@mock.patch.object(ProductSearchClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductSearchAsyncClient)) def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -888,25 +633,18 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -943,24 +681,23 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -991,24 +728,23 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1024,28 +760,16 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1055,50 +779,27 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ProductSearchClient, ProductSearchAsyncClient] -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ProductSearchClient, ProductSearchAsyncClient +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) def test_product_search_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ProductSearchClient._DEFAULT_UNIVERSE - default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1121,19 +822,11 @@ def test_product_search_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1141,40 +834,27 @@ def test_product_search_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), - ], -) -def test_product_search_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), +]) +def test_product_search_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1183,40 +863,24 @@ def test_product_search_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ProductSearchClient, - transports.ProductSearchGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", None), - ], -) -def test_product_search_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", grpc_helpers), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", None), +]) +def test_product_search_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1225,14 +889,11 @@ def test_product_search_client_client_options_credentials_file( api_audience=None, ) - def test_product_search_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ProductSearchClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1247,38 +908,23 @@ def test_product_search_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ProductSearchClient, - transports.ProductSearchGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_product_search_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", grpc_helpers), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_search_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1306,9 +952,9 @@ def test_product_search_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1319,14 +965,11 @@ def test_product_search_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductSetRequest, - dict, - ], -) -def test_create_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductSetRequest, + dict, +]) +def test_create_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1338,12 +981,12 @@ def test_create_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.create_product_set(request) @@ -1355,8 +998,8 @@ def test_create_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_create_product_set_non_empty_request_with_auto_populated_field(): @@ -1364,33 +1007,30 @@ def test_create_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateProductSetRequest( - parent="parent_value", - product_set_id="product_set_id_value", + parent='parent_value', + product_set_id='product_set_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.create_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateProductSetRequest( - parent="parent_value", - product_set_id="product_set_id_value", + parent='parent_value', + product_set_id='product_set_id_value', ) - def test_create_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1405,18 +1045,12 @@ def test_create_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_product_set in client._transport._wrapped_methods - ) + assert client._transport.create_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_product_set] = mock_rpc request = {} client.create_product_set(request) @@ -1429,11 +1063,8 @@ def test_create_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1447,17 +1078,12 @@ async def test_create_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_product_set] = mock_rpc request = {} await client.create_product_set(request) @@ -1471,12 +1097,8 @@ async def test_create_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateProductSetRequest, -): +async def test_create_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1488,15 +1110,13 @@ async def test_create_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.create_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -1507,15 +1127,14 @@ async def test_create_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_create_product_set_async_from_dict(): await test_create_product_set_async(request_type=dict) - def test_create_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1525,12 +1144,12 @@ def test_create_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductSetRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.create_product_set(request) @@ -1542,9 +1161,9 @@ def test_create_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1557,15 +1176,13 @@ async def test_create_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductSetRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + type(client.transport.create_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.create_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -1576,9 +1193,9 @@ async def test_create_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_product_set_flattened(): @@ -1588,16 +1205,16 @@ def test_create_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_product_set( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) # Establish that the underlying call was made with the expected @@ -1605,13 +1222,13 @@ def test_create_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].product_set_id - mock_val = "product_set_id_value" + mock_val = 'product_set_id_value' assert arg == mock_val @@ -1625,12 +1242,11 @@ def test_create_product_set_flattened_error(): with pytest.raises(ValueError): client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) - @pytest.mark.asyncio async def test_create_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -1639,20 +1255,18 @@ async def test_create_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_product_set( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) # Establish that the underlying call was made with the expected @@ -1660,16 +1274,15 @@ async def test_create_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].product_set_id - mock_val = "product_set_id_value" + mock_val = 'product_set_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -1681,20 +1294,17 @@ async def test_create_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductSetsRequest, - dict, - ], -) -def test_list_product_sets(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductSetsRequest, + dict, +]) +def test_list_product_sets(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1706,11 +1316,11 @@ def test_list_product_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_product_sets(request) @@ -1722,7 +1332,7 @@ def test_list_product_sets(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_product_sets_non_empty_request_with_auto_populated_field(): @@ -1730,33 +1340,30 @@ def test_list_product_sets_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductSetsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_product_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_product_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductSetsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_product_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1775,12 +1382,8 @@ def test_list_product_sets_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_product_sets] = mock_rpc request = {} client.list_product_sets(request) @@ -1793,11 +1396,8 @@ def test_list_product_sets_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_product_sets_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1811,17 +1411,12 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_product_sets - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_product_sets in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_product_sets - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_product_sets] = mock_rpc request = {} await client.list_product_sets(request) @@ -1835,12 +1430,8 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_product_sets_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductSetsRequest, -): +async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductSetsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1852,14 +1443,12 @@ async def test_list_product_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse( + next_page_token='next_page_token_value', + )) response = await client.list_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -1870,14 +1459,13 @@ async def test_list_product_sets_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_product_sets_async_from_dict(): await test_list_product_sets_async(request_type=dict) - def test_list_product_sets_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1887,12 +1475,12 @@ def test_list_product_sets_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: call.return_value = product_search_service.ListProductSetsResponse() client.list_product_sets(request) @@ -1904,9 +1492,9 @@ def test_list_product_sets_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1919,15 +1507,13 @@ async def test_list_product_sets_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse() - ) + type(client.transport.list_product_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse()) await client.list_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -1938,9 +1524,9 @@ async def test_list_product_sets_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_product_sets_flattened(): @@ -1950,14 +1536,14 @@ def test_list_product_sets_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_product_sets( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -1965,7 +1551,7 @@ def test_list_product_sets_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -1979,10 +1565,9 @@ def test_list_product_sets_flattened_error(): with pytest.raises(ValueError): client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_product_sets_flattened_async(): client = ProductSearchAsyncClient( @@ -1991,18 +1576,16 @@ async def test_list_product_sets_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_product_sets( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -2010,10 +1593,9 @@ async def test_list_product_sets_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_product_sets_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2025,7 +1607,7 @@ async def test_list_product_sets_flattened_error_async(): with pytest.raises(ValueError): await client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -2037,8 +1619,8 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2047,17 +1629,17 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2072,7 +1654,9 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_product_sets(request={}, retry=retry, timeout=timeout) @@ -2082,9 +1666,8 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in results) - - + assert all(isinstance(i, product_search_service.ProductSet) + for i in results) def test_list_product_sets_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2093,8 +1676,8 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2103,17 +1686,17 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2124,10 +1707,9 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_product_sets(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_product_sets_async_pager(): client = ProductSearchAsyncClient( @@ -2136,10 +1718,8 @@ async def test_list_product_sets_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_product_sets), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2148,17 +1728,17 @@ async def test_list_product_sets_async_pager(): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2168,16 +1748,15 @@ async def test_list_product_sets_async_pager(): ), RuntimeError, ) - async_pager = await client.list_product_sets( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_product_sets(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in responses) + assert all(isinstance(i, product_search_service.ProductSet) + for i in responses) @pytest.mark.asyncio @@ -2188,10 +1767,8 @@ async def test_list_product_sets_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_product_sets), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2200,17 +1777,17 @@ async def test_list_product_sets_async_pages(): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2223,22 +1800,18 @@ async def test_list_product_sets_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_product_sets(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductSetRequest, - dict, - ], -) -def test_get_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductSetRequest, + dict, +]) +def test_get_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2249,11 +1822,13 @@ def test_get_product_set(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.get_product_set(request) @@ -2265,8 +1840,8 @@ def test_get_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_get_product_set_non_empty_request_with_auto_populated_field(): @@ -2274,29 +1849,28 @@ def test_get_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetProductSetRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetProductSetRequest( - name="name_value", + name='name_value', ) - def test_get_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2315,9 +1889,7 @@ def test_get_product_set_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product_set] = mock_rpc request = {} client.get_product_set(request) @@ -2331,11 +1903,8 @@ def test_get_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2349,17 +1918,12 @@ async def test_get_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_product_set] = mock_rpc request = {} await client.get_product_set(request) @@ -2373,12 +1937,8 @@ async def test_get_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetProductSetRequest, -): +async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2389,14 +1949,14 @@ async def test_get_product_set_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.get_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2407,15 +1967,14 @@ async def test_get_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_get_product_set_async_from_dict(): await test_get_product_set_async(request_type=dict) - def test_get_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2425,10 +1984,12 @@ def test_get_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.get_product_set(request) @@ -2440,9 +2001,9 @@ def test_get_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2455,13 +2016,13 @@ async def test_get_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.get_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2472,9 +2033,9 @@ async def test_get_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_product_set_flattened(): @@ -2483,13 +2044,15 @@ def test_get_product_set_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -2497,7 +2060,7 @@ def test_get_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -2511,10 +2074,9 @@ def test_get_product_set_flattened_error(): with pytest.raises(ValueError): client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -2522,17 +2084,17 @@ async def test_get_product_set_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -2540,10 +2102,9 @@ async def test_get_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2555,18 +2116,15 @@ async def test_get_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductSetRequest, - dict, - ], -) -def test_update_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductSetRequest, + dict, +]) +def test_update_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2578,12 +2136,12 @@ def test_update_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.update_product_set(request) @@ -2595,8 +2153,8 @@ def test_update_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_update_product_set_non_empty_request_with_auto_populated_field(): @@ -2604,26 +2162,25 @@ def test_update_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = product_search_service.UpdateProductSetRequest() + request = product_search_service.UpdateProductSetRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.update_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.update_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductSetRequest() - + assert args[0] == product_search_service.UpdateProductSetRequest( + ) def test_update_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2639,18 +2196,12 @@ def test_update_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_product_set in client._transport._wrapped_methods - ) + assert client._transport.update_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_product_set] = mock_rpc request = {} client.update_product_set(request) @@ -2663,11 +2214,8 @@ def test_update_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2681,17 +2229,12 @@ async def test_update_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.update_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.update_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.update_product_set] = mock_rpc request = {} await client.update_product_set(request) @@ -2705,12 +2248,8 @@ async def test_update_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.UpdateProductSetRequest, -): +async def test_update_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.UpdateProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2722,15 +2261,13 @@ async def test_update_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.update_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2741,15 +2278,14 @@ async def test_update_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_update_product_set_async_from_dict(): await test_update_product_set_async(request_type=dict) - def test_update_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2759,12 +2295,12 @@ def test_update_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductSetRequest() - request.product_set.name = "name_value" + request.product_set.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.update_product_set(request) @@ -2776,9 +2312,9 @@ def test_update_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product_set.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product_set.name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2791,15 +2327,13 @@ async def test_update_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductSetRequest() - request.product_set.name = "name_value" + request.product_set.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + type(client.transport.update_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.update_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2810,9 +2344,9 @@ async def test_update_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product_set.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product_set.name=name_value', + ) in kw['metadata'] def test_update_product_set_flattened(): @@ -2822,15 +2356,15 @@ def test_update_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_product_set( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -2838,10 +2372,10 @@ def test_update_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val @@ -2855,11 +2389,10 @@ def test_update_product_set_flattened_error(): with pytest.raises(ValueError): client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) - @pytest.mark.asyncio async def test_update_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -2868,19 +2401,17 @@ async def test_update_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_product_set( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -2888,13 +2419,12 @@ async def test_update_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val - @pytest.mark.asyncio async def test_update_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2906,19 +2436,16 @@ async def test_update_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductSetRequest, - dict, - ], -) -def test_delete_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductSetRequest, + dict, +]) +def test_delete_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2930,8 +2457,8 @@ def test_delete_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_product_set(request) @@ -2951,31 +2478,28 @@ def test_delete_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteProductSetRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.delete_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteProductSetRequest( - name="name_value", + name='name_value', ) - def test_delete_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2990,18 +2514,12 @@ def test_delete_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_product_set in client._transport._wrapped_methods - ) + assert client._transport.delete_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_set] = mock_rpc request = {} client.delete_product_set(request) @@ -3014,11 +2532,8 @@ def test_delete_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3032,17 +2547,12 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_product_set] = mock_rpc request = {} await client.delete_product_set(request) @@ -3056,12 +2566,8 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteProductSetRequest, -): +async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3073,8 +2579,8 @@ async def test_delete_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_product_set(request) @@ -3093,7 +2599,6 @@ async def test_delete_product_set_async( async def test_delete_product_set_async_from_dict(): await test_delete_product_set_async(request_type=dict) - def test_delete_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3103,12 +2608,12 @@ def test_delete_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = None client.delete_product_set(request) @@ -3120,9 +2625,9 @@ def test_delete_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3135,12 +2640,12 @@ async def test_delete_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product_set(request) @@ -3152,9 +2657,9 @@ async def test_delete_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_product_set_flattened(): @@ -3164,14 +2669,14 @@ def test_delete_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -3179,7 +2684,7 @@ def test_delete_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -3193,10 +2698,9 @@ def test_delete_product_set_flattened_error(): with pytest.raises(ValueError): client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -3205,8 +2709,8 @@ async def test_delete_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3214,7 +2718,7 @@ async def test_delete_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -3222,10 +2726,9 @@ async def test_delete_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3237,18 +2740,15 @@ async def test_delete_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductRequest, - dict, - ], -) -def test_create_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3259,13 +2759,15 @@ def test_create_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.create_product(request) @@ -3277,10 +2779,10 @@ def test_create_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_create_product_non_empty_request_with_auto_populated_field(): @@ -3288,31 +2790,30 @@ def test_create_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateProductRequest( - parent="parent_value", - product_id="product_id_value", + parent='parent_value', + product_id='product_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateProductRequest( - parent="parent_value", - product_id="product_id_value", + parent='parent_value', + product_id='product_id_value', ) - def test_create_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3331,9 +2832,7 @@ def test_create_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.create_product] = mock_rpc request = {} client.create_product(request) @@ -3347,11 +2846,8 @@ def test_create_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3365,17 +2861,12 @@ async def test_create_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_product] = mock_rpc request = {} await client.create_product(request) @@ -3389,12 +2880,8 @@ async def test_create_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateProductRequest, -): +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3405,16 +2892,16 @@ async def test_create_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.create_product(request) # Establish that the underlying gRPC stub method was called. @@ -3425,17 +2912,16 @@ async def test_create_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_create_product_async_from_dict(): await test_create_product_async(request_type=dict) - def test_create_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3445,10 +2931,12 @@ def test_create_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: call.return_value = product_search_service.Product() client.create_product(request) @@ -3460,9 +2948,9 @@ def test_create_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3475,13 +2963,13 @@ async def test_create_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.create_product(request) # Establish that the underlying gRPC stub method was called. @@ -3492,9 +2980,9 @@ async def test_create_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_product_flattened(): @@ -3503,15 +2991,17 @@ def test_create_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_product( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) # Establish that the underlying call was made with the expected @@ -3519,13 +3009,13 @@ def test_create_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].product_id - mock_val = "product_id_value" + mock_val = 'product_id_value' assert arg == mock_val @@ -3539,12 +3029,11 @@ def test_create_product_flattened_error(): with pytest.raises(ValueError): client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) - @pytest.mark.asyncio async def test_create_product_flattened_async(): client = ProductSearchAsyncClient( @@ -3552,19 +3041,19 @@ async def test_create_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_product( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) # Establish that the underlying call was made with the expected @@ -3572,16 +3061,15 @@ async def test_create_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].product_id - mock_val = "product_id_value" + mock_val = 'product_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3593,20 +3081,17 @@ async def test_create_product_flattened_error_async(): with pytest.raises(ValueError): await client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsRequest, - dict, - ], -) -def test_list_products(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3617,10 +3102,12 @@ def test_list_products(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_products(request) @@ -3632,7 +3119,7 @@ def test_list_products(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_products_non_empty_request_with_auto_populated_field(): @@ -3640,31 +3127,30 @@ def test_list_products_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_products(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_products_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3683,9 +3169,7 @@ def test_list_products_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} client.list_products(request) @@ -3699,11 +3183,8 @@ def test_list_products_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3717,17 +3198,12 @@ async def test_list_products_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_products - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_products in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_products - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_products] = mock_rpc request = {} await client.list_products(request) @@ -3741,12 +3217,8 @@ async def test_list_products_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductsRequest, -): +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3757,13 +3229,13 @@ async def test_list_products_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) response = await client.list_products(request) # Establish that the underlying gRPC stub method was called. @@ -3774,14 +3246,13 @@ async def test_list_products_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_products_async_from_dict(): await test_list_products_async(request_type=dict) - def test_list_products_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3791,10 +3262,12 @@ def test_list_products_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: call.return_value = product_search_service.ListProductsResponse() client.list_products(request) @@ -3806,9 +3279,9 @@ def test_list_products_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3821,13 +3294,13 @@ async def test_list_products_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse() - ) + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse()) await client.list_products(request) # Establish that the underlying gRPC stub method was called. @@ -3838,9 +3311,9 @@ async def test_list_products_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_products_flattened(): @@ -3849,13 +3322,15 @@ def test_list_products_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -3863,7 +3338,7 @@ def test_list_products_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -3877,10 +3352,9 @@ def test_list_products_flattened_error(): with pytest.raises(ValueError): client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_products_flattened_async(): client = ProductSearchAsyncClient( @@ -3888,17 +3362,17 @@ async def test_list_products_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -3906,10 +3380,9 @@ async def test_list_products_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_products_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3921,7 +3394,7 @@ async def test_list_products_flattened_error_async(): with pytest.raises(ValueError): await client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -3932,7 +3405,9 @@ def test_list_products_pager(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -3941,17 +3416,17 @@ def test_list_products_pager(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -3966,7 +3441,9 @@ def test_list_products_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_products(request={}, retry=retry, timeout=timeout) @@ -3976,9 +3453,8 @@ def test_list_products_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) - - + assert all(isinstance(i, product_search_service.Product) + for i in results) def test_list_products_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3986,7 +3462,9 @@ def test_list_products_pages(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -3995,17 +3473,17 @@ def test_list_products_pages(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4016,10 +3494,9 @@ def test_list_products_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_products(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_products_async_pager(): client = ProductSearchAsyncClient( @@ -4028,8 +3505,8 @@ async def test_list_products_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products), "__call__", new_callable=mock.AsyncMock - ) as call: + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -4038,17 +3515,17 @@ async def test_list_products_async_pager(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4058,16 +3535,15 @@ async def test_list_products_async_pager(): ), RuntimeError, ) - async_pager = await client.list_products( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_products(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.Product) for i in responses) + assert all(isinstance(i, product_search_service.Product) + for i in responses) @pytest.mark.asyncio @@ -4078,8 +3554,8 @@ async def test_list_products_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products), "__call__", new_callable=mock.AsyncMock - ) as call: + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -4088,17 +3564,17 @@ async def test_list_products_async_pages(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4111,22 +3587,18 @@ async def test_list_products_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_products(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductRequest, - dict, - ], -) -def test_get_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4137,13 +3609,15 @@ def test_get_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.get_product(request) @@ -4155,10 +3629,10 @@ def test_get_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_get_product_non_empty_request_with_auto_populated_field(): @@ -4166,29 +3640,28 @@ def test_get_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetProductRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetProductRequest( - name="name_value", + name='name_value', ) - def test_get_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4207,9 +3680,7 @@ def test_get_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product] = mock_rpc request = {} client.get_product(request) @@ -4223,11 +3694,8 @@ def test_get_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4241,17 +3709,12 @@ async def test_get_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_product] = mock_rpc request = {} await client.get_product(request) @@ -4265,12 +3728,8 @@ async def test_get_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetProductRequest, -): +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4281,16 +3740,16 @@ async def test_get_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.get_product(request) # Establish that the underlying gRPC stub method was called. @@ -4301,17 +3760,16 @@ async def test_get_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_get_product_async_from_dict(): await test_get_product_async(request_type=dict) - def test_get_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4321,10 +3779,12 @@ def test_get_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: call.return_value = product_search_service.Product() client.get_product(request) @@ -4336,9 +3796,9 @@ def test_get_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -4351,13 +3811,13 @@ async def test_get_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.get_product(request) # Establish that the underlying gRPC stub method was called. @@ -4368,9 +3828,9 @@ async def test_get_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_product_flattened(): @@ -4379,13 +3839,15 @@ def test_get_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -4393,7 +3855,7 @@ def test_get_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -4407,10 +3869,9 @@ def test_get_product_flattened_error(): with pytest.raises(ValueError): client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_product_flattened_async(): client = ProductSearchAsyncClient( @@ -4418,17 +3879,17 @@ async def test_get_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -4436,10 +3897,9 @@ async def test_get_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -4451,18 +3911,15 @@ async def test_get_product_flattened_error_async(): with pytest.raises(ValueError): await client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductRequest, - dict, - ], -) -def test_update_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4473,13 +3930,15 @@ def test_update_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.update_product(request) @@ -4491,10 +3950,10 @@ def test_update_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_update_product_non_empty_request_with_auto_populated_field(): @@ -4502,24 +3961,25 @@ def test_update_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = product_search_service.UpdateProductRequest() + request = product_search_service.UpdateProductRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.update_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductRequest() - + assert args[0] == product_search_service.UpdateProductRequest( + ) def test_update_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4539,9 +3999,7 @@ def test_update_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} client.update_product(request) @@ -4555,11 +4013,8 @@ def test_update_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4573,17 +4028,12 @@ async def test_update_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.update_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.update_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.update_product] = mock_rpc request = {} await client.update_product(request) @@ -4597,12 +4047,8 @@ async def test_update_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.UpdateProductRequest, -): +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.UpdateProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4613,16 +4059,16 @@ async def test_update_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.update_product(request) # Establish that the underlying gRPC stub method was called. @@ -4633,17 +4079,16 @@ async def test_update_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_update_product_async_from_dict(): await test_update_product_async(request_type=dict) - def test_update_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4653,10 +4098,12 @@ def test_update_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductRequest() - request.product.name = "name_value" + request.product.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: call.return_value = product_search_service.Product() client.update_product(request) @@ -4668,9 +4115,9 @@ def test_update_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -4683,13 +4130,13 @@ async def test_update_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductRequest() - request.product.name = "name_value" + request.product.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.update_product(request) # Establish that the underlying gRPC stub method was called. @@ -4700,9 +4147,9 @@ async def test_update_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] def test_update_product_flattened(): @@ -4711,14 +4158,16 @@ def test_update_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_product( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -4726,10 +4175,10 @@ def test_update_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val @@ -4743,11 +4192,10 @@ def test_update_product_flattened_error(): with pytest.raises(ValueError): client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) - @pytest.mark.asyncio async def test_update_product_flattened_async(): client = ProductSearchAsyncClient( @@ -4755,18 +4203,18 @@ async def test_update_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_product( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -4774,13 +4222,12 @@ async def test_update_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val - @pytest.mark.asyncio async def test_update_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -4792,19 +4239,16 @@ async def test_update_product_flattened_error_async(): with pytest.raises(ValueError): await client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductRequest, - dict, - ], -) -def test_delete_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4815,7 +4259,9 @@ def test_delete_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_product(request) @@ -4835,29 +4281,28 @@ def test_delete_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteProductRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteProductRequest( - name="name_value", + name='name_value', ) - def test_delete_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4876,9 +4321,7 @@ def test_delete_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc request = {} client.delete_product(request) @@ -4892,11 +4335,8 @@ def test_delete_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4910,17 +4350,12 @@ async def test_delete_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_product] = mock_rpc request = {} await client.delete_product(request) @@ -4934,12 +4369,8 @@ async def test_delete_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteProductRequest, -): +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4950,7 +4381,9 @@ async def test_delete_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_product(request) @@ -4969,7 +4402,6 @@ async def test_delete_product_async( async def test_delete_product_async_from_dict(): await test_delete_product_async(request_type=dict) - def test_delete_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4979,10 +4411,12 @@ def test_delete_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = None client.delete_product(request) @@ -4994,9 +4428,9 @@ def test_delete_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5009,10 +4443,12 @@ async def test_delete_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product(request) @@ -5024,9 +4460,9 @@ async def test_delete_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_product_flattened(): @@ -5035,13 +4471,15 @@ def test_delete_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5049,7 +4487,7 @@ def test_delete_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -5063,10 +4501,9 @@ def test_delete_product_flattened_error(): with pytest.raises(ValueError): client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_product_flattened_async(): client = ProductSearchAsyncClient( @@ -5074,7 +4511,9 @@ async def test_delete_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -5082,7 +4521,7 @@ async def test_delete_product_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5090,10 +4529,9 @@ async def test_delete_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5105,18 +4543,15 @@ async def test_delete_product_flattened_error_async(): with pytest.raises(ValueError): await client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateReferenceImageRequest, - dict, - ], -) -def test_create_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateReferenceImageRequest, + dict, +]) +def test_create_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5128,12 +4563,12 @@ def test_create_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) response = client.create_reference_image(request) @@ -5145,8 +4580,8 @@ def test_create_reference_image(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' def test_create_reference_image_non_empty_request_with_auto_populated_field(): @@ -5154,33 +4589,30 @@ def test_create_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateReferenceImageRequest( - parent="parent_value", - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image_id='reference_image_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.create_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateReferenceImageRequest( - parent="parent_value", - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image_id='reference_image_id_value', ) - def test_create_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5195,19 +4627,12 @@ def test_create_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.create_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_reference_image] = mock_rpc request = {} client.create_reference_image(request) @@ -5220,11 +4645,8 @@ def test_create_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5238,17 +4660,12 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_reference_image] = mock_rpc request = {} await client.create_reference_image(request) @@ -5262,12 +4679,8 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateReferenceImageRequest, -): +async def test_create_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5279,15 +4692,13 @@ async def test_create_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) response = await client.create_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -5298,15 +4709,14 @@ async def test_create_reference_image_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.asyncio async def test_create_reference_image_async_from_dict(): await test_create_reference_image_async(request_type=dict) - def test_create_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5316,12 +4726,12 @@ def test_create_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateReferenceImageRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.create_reference_image(request) @@ -5333,9 +4743,9 @@ def test_create_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5348,15 +4758,13 @@ async def test_create_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateReferenceImageRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + type(client.transport.create_reference_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) await client.create_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -5367,9 +4775,9 @@ async def test_create_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_reference_image_flattened(): @@ -5379,16 +4787,16 @@ def test_create_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_reference_image( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) # Establish that the underlying call was made with the expected @@ -5396,13 +4804,13 @@ def test_create_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].reference_image - mock_val = product_search_service.ReferenceImage(name="name_value") + mock_val = product_search_service.ReferenceImage(name='name_value') assert arg == mock_val arg = args[0].reference_image_id - mock_val = "reference_image_id_value" + mock_val = 'reference_image_id_value' assert arg == mock_val @@ -5416,12 +4824,11 @@ def test_create_reference_image_flattened_error(): with pytest.raises(ValueError): client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) - @pytest.mark.asyncio async def test_create_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -5430,20 +4837,18 @@ async def test_create_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_reference_image( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) # Establish that the underlying call was made with the expected @@ -5451,16 +4856,15 @@ async def test_create_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].reference_image - mock_val = product_search_service.ReferenceImage(name="name_value") + mock_val = product_search_service.ReferenceImage(name='name_value') assert arg == mock_val arg = args[0].reference_image_id - mock_val = "reference_image_id_value" + mock_val = 'reference_image_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5472,20 +4876,17 @@ async def test_create_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteReferenceImageRequest, - dict, - ], -) -def test_delete_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteReferenceImageRequest, + dict, +]) +def test_delete_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5497,8 +4898,8 @@ def test_delete_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_reference_image(request) @@ -5518,31 +4919,28 @@ def test_delete_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteReferenceImageRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.delete_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteReferenceImageRequest( - name="name_value", + name='name_value', ) - def test_delete_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5557,19 +4955,12 @@ def test_delete_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.delete_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_reference_image] = mock_rpc request = {} client.delete_reference_image(request) @@ -5582,11 +4973,8 @@ def test_delete_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5600,17 +4988,12 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_reference_image] = mock_rpc request = {} await client.delete_reference_image(request) @@ -5624,12 +5007,8 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteReferenceImageRequest, -): +async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5641,8 +5020,8 @@ async def test_delete_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_reference_image(request) @@ -5661,7 +5040,6 @@ async def test_delete_reference_image_async( async def test_delete_reference_image_async_from_dict(): await test_delete_reference_image_async(request_type=dict) - def test_delete_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5671,12 +5049,12 @@ def test_delete_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = None client.delete_reference_image(request) @@ -5688,9 +5066,9 @@ def test_delete_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5703,12 +5081,12 @@ async def test_delete_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_reference_image(request) @@ -5720,9 +5098,9 @@ async def test_delete_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_reference_image_flattened(): @@ -5732,14 +5110,14 @@ def test_delete_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5747,7 +5125,7 @@ def test_delete_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -5761,10 +5139,9 @@ def test_delete_reference_image_flattened_error(): with pytest.raises(ValueError): client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -5773,8 +5150,8 @@ async def test_delete_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -5782,7 +5159,7 @@ async def test_delete_reference_image_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5790,10 +5167,9 @@ async def test_delete_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5805,18 +5181,15 @@ async def test_delete_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListReferenceImagesRequest, - dict, - ], -) -def test_list_reference_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListReferenceImagesRequest, + dict, +]) +def test_list_reference_images(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5828,12 +5201,12 @@ def test_list_reference_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse( page_size=951, - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_reference_images(request) @@ -5846,7 +5219,7 @@ def test_list_reference_images(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_reference_images_non_empty_request_with_auto_populated_field(): @@ -5854,33 +5227,30 @@ def test_list_reference_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListReferenceImagesRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_reference_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_reference_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListReferenceImagesRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_reference_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5895,19 +5265,12 @@ def test_list_reference_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_reference_images - in client._transport._wrapped_methods - ) + assert client._transport.list_reference_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reference_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_reference_images] = mock_rpc request = {} client.list_reference_images(request) @@ -5920,11 +5283,8 @@ def test_list_reference_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_reference_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5938,17 +5298,12 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_reference_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_reference_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_reference_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_reference_images] = mock_rpc request = {} await client.list_reference_images(request) @@ -5962,12 +5317,8 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_reference_images_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListReferenceImagesRequest, -): +async def test_list_reference_images_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListReferenceImagesRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5979,15 +5330,13 @@ async def test_list_reference_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse( + page_size=951, + next_page_token='next_page_token_value', + )) response = await client.list_reference_images(request) # Establish that the underlying gRPC stub method was called. @@ -5999,14 +5348,13 @@ async def test_list_reference_images_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesAsyncPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_reference_images_async_from_dict(): await test_list_reference_images_async(request_type=dict) - def test_list_reference_images_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6016,12 +5364,12 @@ def test_list_reference_images_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListReferenceImagesRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: call.return_value = product_search_service.ListReferenceImagesResponse() client.list_reference_images(request) @@ -6033,9 +5381,9 @@ def test_list_reference_images_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6048,15 +5396,13 @@ async def test_list_reference_images_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListReferenceImagesRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse() - ) + type(client.transport.list_reference_images), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse()) await client.list_reference_images(request) # Establish that the underlying gRPC stub method was called. @@ -6067,9 +5413,9 @@ async def test_list_reference_images_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_reference_images_flattened(): @@ -6079,14 +5425,14 @@ def test_list_reference_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_reference_images( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -6094,7 +5440,7 @@ def test_list_reference_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -6108,10 +5454,9 @@ def test_list_reference_images_flattened_error(): with pytest.raises(ValueError): client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_reference_images_flattened_async(): client = ProductSearchAsyncClient( @@ -6120,18 +5465,16 @@ async def test_list_reference_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_reference_images( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -6139,10 +5482,9 @@ async def test_list_reference_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_reference_images_flattened_error_async(): client = ProductSearchAsyncClient( @@ -6154,7 +5496,7 @@ async def test_list_reference_images_flattened_error_async(): with pytest.raises(ValueError): await client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) @@ -6166,8 +5508,8 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6176,17 +5518,17 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6201,7 +5543,9 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_reference_images(request={}, retry=retry, timeout=timeout) @@ -6211,11 +5555,8 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in results - ) - - + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in results) def test_list_reference_images_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6224,8 +5565,8 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6234,17 +5575,17 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6255,10 +5596,9 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_reference_images(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_reference_images_async_pager(): client = ProductSearchAsyncClient( @@ -6267,10 +5607,8 @@ async def test_list_reference_images_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_reference_images), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6279,17 +5617,17 @@ async def test_list_reference_images_async_pager(): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6299,18 +5637,15 @@ async def test_list_reference_images_async_pager(): ), RuntimeError, ) - async_pager = await client.list_reference_images( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_reference_images(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in responses - ) + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in responses) @pytest.mark.asyncio @@ -6321,10 +5656,8 @@ async def test_list_reference_images_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_reference_images), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6333,17 +5666,17 @@ async def test_list_reference_images_async_pages(): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6356,22 +5689,18 @@ async def test_list_reference_images_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_reference_images(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetReferenceImageRequest, - dict, - ], -) -def test_get_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetReferenceImageRequest, + dict, +]) +def test_get_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6383,12 +5712,12 @@ def test_get_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) response = client.get_reference_image(request) @@ -6400,8 +5729,8 @@ def test_get_reference_image(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' def test_get_reference_image_non_empty_request_with_auto_populated_field(): @@ -6409,31 +5738,28 @@ def test_get_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetReferenceImageRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.get_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetReferenceImageRequest( - name="name_value", + name='name_value', ) - def test_get_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6448,18 +5774,12 @@ def test_get_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_reference_image in client._transport._wrapped_methods - ) + assert client._transport.get_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_reference_image] = mock_rpc request = {} client.get_reference_image(request) @@ -6472,11 +5792,8 @@ def test_get_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -6490,17 +5807,12 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_reference_image] = mock_rpc request = {} await client.get_reference_image(request) @@ -6514,12 +5826,8 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetReferenceImageRequest, -): +async def test_get_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6531,15 +5839,13 @@ async def test_get_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) response = await client.get_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -6550,15 +5856,14 @@ async def test_get_reference_image_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.asyncio async def test_get_reference_image_async_from_dict(): await test_get_reference_image_async(request_type=dict) - def test_get_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6568,12 +5873,12 @@ def test_get_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.get_reference_image(request) @@ -6585,9 +5890,9 @@ def test_get_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6600,15 +5905,13 @@ async def test_get_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + type(client.transport.get_reference_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) await client.get_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -6619,9 +5922,9 @@ async def test_get_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_reference_image_flattened(): @@ -6631,14 +5934,14 @@ def test_get_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -6646,7 +5949,7 @@ def test_get_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -6660,10 +5963,9 @@ def test_get_reference_image_flattened_error(): with pytest.raises(ValueError): client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -6672,18 +5974,16 @@ async def test_get_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -6691,10 +5991,9 @@ async def test_get_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -6706,18 +6005,15 @@ async def test_get_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.AddProductToProductSetRequest, - dict, - ], -) -def test_add_product_to_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.AddProductToProductSetRequest, + dict, +]) +def test_add_product_to_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6729,8 +6025,8 @@ def test_add_product_to_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.add_product_to_product_set(request) @@ -6750,33 +6046,30 @@ def test_add_product_to_product_set_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.AddProductToProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.add_product_to_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.add_product_to_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.AddProductToProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - def test_add_product_to_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6791,19 +6084,12 @@ def test_add_product_to_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.add_product_to_product_set - in client._transport._wrapped_methods - ) + assert client._transport.add_product_to_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_product_to_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_product_to_product_set] = mock_rpc request = {} client.add_product_to_product_set(request) @@ -6816,11 +6102,8 @@ def test_add_product_to_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -6834,17 +6117,12 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.add_product_to_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.add_product_to_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.add_product_to_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.add_product_to_product_set] = mock_rpc request = {} await client.add_product_to_product_set(request) @@ -6858,12 +6136,8 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_add_product_to_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.AddProductToProductSetRequest, -): +async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.AddProductToProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6875,8 +6149,8 @@ async def test_add_product_to_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.add_product_to_product_set(request) @@ -6895,7 +6169,6 @@ async def test_add_product_to_product_set_async( async def test_add_product_to_product_set_async_from_dict(): await test_add_product_to_product_set_async(request_type=dict) - def test_add_product_to_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6905,12 +6178,12 @@ def test_add_product_to_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.AddProductToProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = None client.add_product_to_product_set(request) @@ -6922,9 +6195,9 @@ def test_add_product_to_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6937,12 +6210,12 @@ async def test_add_product_to_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.AddProductToProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.add_product_to_product_set(request) @@ -6954,9 +6227,9 @@ async def test_add_product_to_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_add_product_to_product_set_flattened(): @@ -6966,15 +6239,15 @@ def test_add_product_to_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.add_product_to_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -6982,10 +6255,10 @@ def test_add_product_to_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val @@ -6999,11 +6272,10 @@ def test_add_product_to_product_set_flattened_error(): with pytest.raises(ValueError): client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7012,8 +6284,8 @@ async def test_add_product_to_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -7021,8 +6293,8 @@ async def test_add_product_to_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.add_product_to_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7030,13 +6302,12 @@ async def test_add_product_to_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val - @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7048,19 +6319,16 @@ async def test_add_product_to_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.RemoveProductFromProductSetRequest, - dict, - ], -) -def test_remove_product_from_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.RemoveProductFromProductSetRequest, + dict, +]) +def test_remove_product_from_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7072,8 +6340,8 @@ def test_remove_product_from_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.remove_product_from_product_set(request) @@ -7093,33 +6361,30 @@ def test_remove_product_from_product_set_non_empty_request_with_auto_populated_f # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.RemoveProductFromProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.remove_product_from_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.remove_product_from_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.RemoveProductFromProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - def test_remove_product_from_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7134,19 +6399,12 @@ def test_remove_product_from_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.remove_product_from_product_set - in client._transport._wrapped_methods - ) + assert client._transport.remove_product_from_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_product_from_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_product_from_product_set] = mock_rpc request = {} client.remove_product_from_product_set(request) @@ -7159,11 +6417,8 @@ def test_remove_product_from_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7177,17 +6432,12 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.remove_product_from_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.remove_product_from_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.remove_product_from_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.remove_product_from_product_set] = mock_rpc request = {} await client.remove_product_from_product_set(request) @@ -7201,12 +6451,8 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_remove_product_from_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.RemoveProductFromProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7218,8 +6464,8 @@ async def test_remove_product_from_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.remove_product_from_product_set(request) @@ -7238,7 +6484,6 @@ async def test_remove_product_from_product_set_async( async def test_remove_product_from_product_set_async_from_dict(): await test_remove_product_from_product_set_async(request_type=dict) - def test_remove_product_from_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7248,12 +6493,12 @@ def test_remove_product_from_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.RemoveProductFromProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = None client.remove_product_from_product_set(request) @@ -7265,9 +6510,9 @@ def test_remove_product_from_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -7280,12 +6525,12 @@ async def test_remove_product_from_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.RemoveProductFromProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.remove_product_from_product_set(request) @@ -7297,9 +6542,9 @@ async def test_remove_product_from_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_remove_product_from_product_set_flattened(): @@ -7309,15 +6554,15 @@ def test_remove_product_from_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.remove_product_from_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7325,10 +6570,10 @@ def test_remove_product_from_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val @@ -7342,11 +6587,10 @@ def test_remove_product_from_product_set_flattened_error(): with pytest.raises(ValueError): client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7355,8 +6599,8 @@ async def test_remove_product_from_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -7364,8 +6608,8 @@ async def test_remove_product_from_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.remove_product_from_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7373,13 +6617,12 @@ async def test_remove_product_from_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val - @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7391,19 +6634,16 @@ async def test_remove_product_from_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsInProductSetRequest, - dict, - ], -) -def test_list_products_in_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsInProductSetRequest, + dict, +]) +def test_list_products_in_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7415,11 +6655,11 @@ def test_list_products_in_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_products_in_product_set(request) @@ -7431,7 +6671,7 @@ def test_list_products_in_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_products_in_product_set_non_empty_request_with_auto_populated_field(): @@ -7439,33 +6679,30 @@ def test_list_products_in_product_set_non_empty_request_with_auto_populated_fiel # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductsInProductSetRequest( - name="name_value", - page_token="page_token_value", + name='name_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_products_in_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_products_in_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductsInProductSetRequest( - name="name_value", - page_token="page_token_value", + name='name_value', + page_token='page_token_value', ) - def test_list_products_in_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7480,19 +6717,12 @@ def test_list_products_in_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_products_in_product_set - in client._transport._wrapped_methods - ) + assert client._transport.list_products_in_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_products_in_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products_in_product_set] = mock_rpc request = {} client.list_products_in_product_set(request) @@ -7505,11 +6735,8 @@ def test_list_products_in_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7523,17 +6750,12 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_products_in_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_products_in_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_products_in_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_products_in_product_set] = mock_rpc request = {} await client.list_products_in_product_set(request) @@ -7547,12 +6769,8 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_in_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductsInProductSetRequest, -): +async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductsInProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7564,14 +6782,12 @@ async def test_list_products_in_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse( + next_page_token='next_page_token_value', + )) response = await client.list_products_in_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -7582,14 +6798,13 @@ async def test_list_products_in_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_products_in_product_set_async_from_dict(): await test_list_products_in_product_set_async(request_type=dict) - def test_list_products_in_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7599,12 +6814,12 @@ def test_list_products_in_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsInProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: call.return_value = product_search_service.ListProductsInProductSetResponse() client.list_products_in_product_set(request) @@ -7616,9 +6831,9 @@ def test_list_products_in_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -7631,15 +6846,13 @@ async def test_list_products_in_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsInProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse() - ) + type(client.transport.list_products_in_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse()) await client.list_products_in_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -7650,9 +6863,9 @@ async def test_list_products_in_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_list_products_in_product_set_flattened(): @@ -7662,14 +6875,14 @@ def test_list_products_in_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_products_in_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -7677,7 +6890,7 @@ def test_list_products_in_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -7691,10 +6904,9 @@ def test_list_products_in_product_set_flattened_error(): with pytest.raises(ValueError): client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7703,18 +6915,16 @@ async def test_list_products_in_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse() - ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_products_in_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -7722,10 +6932,9 @@ async def test_list_products_in_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7737,7 +6946,7 @@ async def test_list_products_in_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) @@ -7749,8 +6958,8 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7759,17 +6968,17 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7784,11 +6993,11 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), - ) - pager = client.list_products_in_product_set( - request={}, retry=retry, timeout=timeout + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), ) + pager = client.list_products_in_product_set(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7796,9 +7005,8 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) - - + assert all(isinstance(i, product_search_service.Product) + for i in results) def test_list_products_in_product_set_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7807,8 +7015,8 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7817,17 +7025,17 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7838,10 +7046,9 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_products_in_product_set(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_products_in_product_set_async_pager(): client = ProductSearchAsyncClient( @@ -7850,10 +7057,8 @@ async def test_list_products_in_product_set_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_products_in_product_set), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7862,17 +7067,17 @@ async def test_list_products_in_product_set_async_pager(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7882,16 +7087,15 @@ async def test_list_products_in_product_set_async_pager(): ), RuntimeError, ) - async_pager = await client.list_products_in_product_set( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_products_in_product_set(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.Product) for i in responses) + assert all(isinstance(i, product_search_service.Product) + for i in responses) @pytest.mark.asyncio @@ -7902,10 +7106,8 @@ async def test_list_products_in_product_set_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_products_in_product_set), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7914,17 +7116,17 @@ async def test_list_products_in_product_set_async_pages(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7937,22 +7139,18 @@ async def test_list_products_in_product_set_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_products_in_product_set(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ImportProductSetsRequest, - dict, - ], -) -def test_import_product_sets(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ImportProductSetsRequest, + dict, +]) +def test_import_product_sets(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7964,10 +7162,10 @@ def test_import_product_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -7985,31 +7183,28 @@ def test_import_product_sets_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ImportProductSetsRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.import_product_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ImportProductSetsRequest( - parent="parent_value", + parent='parent_value', ) - def test_import_product_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8024,18 +7219,12 @@ def test_import_product_sets_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.import_product_sets in client._transport._wrapped_methods - ) + assert client._transport.import_product_sets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_product_sets] = mock_rpc request = {} client.import_product_sets(request) @@ -8053,11 +7242,8 @@ def test_import_product_sets_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_import_product_sets_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -8071,17 +7257,12 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.import_product_sets - in client._client._transport._wrapped_methods - ) + assert client._client._transport.import_product_sets in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.import_product_sets - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.import_product_sets] = mock_rpc request = {} await client.import_product_sets(request) @@ -8100,12 +7281,8 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_import_product_sets_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ImportProductSetsRequest, -): +async def test_import_product_sets_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ImportProductSetsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8117,11 +7294,11 @@ async def test_import_product_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.import_product_sets(request) @@ -8139,7 +7316,6 @@ async def test_import_product_sets_async( async def test_import_product_sets_async_from_dict(): await test_import_product_sets_async(request_type=dict) - def test_import_product_sets_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8149,13 +7325,13 @@ def test_import_product_sets_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ImportProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -8166,9 +7342,9 @@ def test_import_product_sets_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -8181,15 +7357,13 @@ async def test_import_product_sets_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ImportProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) await client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -8200,9 +7374,9 @@ async def test_import_product_sets_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_import_product_sets_flattened(): @@ -8212,19 +7386,15 @@ def test_import_product_sets_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.import_product_sets( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) # Establish that the underlying call was made with the expected @@ -8232,14 +7402,10 @@ def test_import_product_sets_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].input_config - mock_val = product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ) + mock_val = product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')) assert arg == mock_val @@ -8253,15 +7419,10 @@ def test_import_product_sets_flattened_error(): with pytest.raises(ValueError): client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) - @pytest.mark.asyncio async def test_import_product_sets_flattened_async(): client = ProductSearchAsyncClient( @@ -8270,23 +7431,19 @@ async def test_import_product_sets_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.import_product_sets( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) # Establish that the underlying call was made with the expected @@ -8294,17 +7451,12 @@ async def test_import_product_sets_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].input_config - mock_val = product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ) + mock_val = product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')) assert arg == mock_val - @pytest.mark.asyncio async def test_import_product_sets_flattened_error_async(): client = ProductSearchAsyncClient( @@ -8316,12 +7468,8 @@ async def test_import_product_sets_flattened_error_async(): with pytest.raises(ValueError): await client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) @@ -8339,18 +7487,12 @@ def test_create_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_product_set in client._transport._wrapped_methods - ) + assert client._transport.create_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_product_set] = mock_rpc request = {} client.create_product_set(request) @@ -8365,64 +7507,59 @@ def test_create_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_product_set_rest_required_fields( - request_type=product_search_service.CreateProductSetRequest, -): +def test_create_product_set_rest_required_fields(request_type=product_search_service.CreateProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product_set._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("product_set_id",)) + assert not set(unset_fields) - set(("product_set_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -8432,32 +7569,24 @@ def test_create_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("productSetId",)) - & set( - ( - "parent", - "productSet", - ) - ) - ) + assert set(unset_fields) == (set(("productSetId", )) & set(("parent", "productSet", ))) def test_create_product_set_rest_flattened(): @@ -8467,18 +7596,18 @@ def test_create_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) mock_args.update(sample_request) @@ -8488,7 +7617,7 @@ def test_create_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -8498,14 +7627,10 @@ def test_create_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*}/productSets" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*}/productSets" % client.transport._host, args[1]) -def test_create_product_set_rest_flattened_error(transport: str = "rest"): +def test_create_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8516,9 +7641,9 @@ def test_create_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) @@ -8540,12 +7665,8 @@ def test_list_product_sets_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_product_sets] = mock_rpc request = {} client.list_product_sets(request) @@ -8560,67 +7681,57 @@ def test_list_product_sets_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_product_sets_rest_required_fields( - request_type=product_search_service.ListProductSetsRequest, -): +def test_list_product_sets_rest_required_fields(request_type=product_search_service.ListProductSetsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_product_sets._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_product_sets._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -8628,37 +7739,27 @@ def test_list_product_sets_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductSetsResponse.pb( - return_value - ) + return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_product_sets(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_product_sets_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_product_sets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_product_sets_rest_flattened(): @@ -8668,16 +7769,16 @@ def test_list_product_sets_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -8687,7 +7788,7 @@ def test_list_product_sets_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -8697,14 +7798,10 @@ def test_list_product_sets_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*}/productSets" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*}/productSets" % client.transport._host, args[1]) -def test_list_product_sets_rest_flattened_error(transport: str = "rest"): +def test_list_product_sets_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8715,20 +7812,20 @@ def test_list_product_sets_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_product_sets_rest_pager(transport: str = "rest"): +def test_list_product_sets_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductSetsResponse( @@ -8737,17 +7834,17 @@ def test_list_product_sets_rest_pager(transport: str = "rest"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -8760,25 +7857,24 @@ def test_list_product_sets_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductSetsResponse.to_json(x) for x in response - ) + response = tuple(product_search_service.ListProductSetsResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} pager = client.list_product_sets(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in results) + assert all(isinstance(i, product_search_service.ProductSet) + for i in results) pages = list(client.list_product_sets(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -8800,9 +7896,7 @@ def test_get_product_set_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product_set] = mock_rpc request = {} @@ -8818,60 +7912,55 @@ def test_get_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_product_set_rest_required_fields( - request_type=product_search_service.GetProductSetRequest, -): +def test_get_product_set_rest_required_fields(request_type=product_search_service.GetProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -8882,24 +7971,24 @@ def test_get_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_product_set_rest_flattened(): @@ -8909,18 +7998,16 @@ def test_get_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -8930,7 +8017,7 @@ def test_get_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -8940,14 +8027,10 @@ def test_get_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_get_product_set_rest_flattened_error(transport: str = "rest"): +def test_get_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8958,7 +8041,7 @@ def test_get_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) @@ -8976,18 +8059,12 @@ def test_update_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_product_set in client._transport._wrapped_methods - ) + assert client._transport.update_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_product_set] = mock_rpc request = {} client.update_product_set(request) @@ -9002,59 +8079,54 @@ def test_update_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_product_set_rest_required_fields( - request_type=product_search_service.UpdateProductSetRequest, -): +def test_update_product_set_rest_required_fields(request_type=product_search_service.UpdateProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("update_mask", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9064,24 +8136,24 @@ def test_update_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_update_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.update_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("productSet",))) + assert set(unset_fields) == (set(("updateMask", )) & set(("productSet", ))) def test_update_product_set_rest_flattened(): @@ -9091,21 +8163,17 @@ def test_update_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } + sample_request = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/sample3'}} # get truthy value for each flattened field mock_args = dict( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) mock_args.update(sample_request) @@ -9115,7 +8183,7 @@ def test_update_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9125,14 +8193,10 @@ def test_update_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_update_product_set_rest_flattened_error(transport: str = "rest"): +def test_update_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9143,8 +8207,8 @@ def test_update_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) @@ -9162,18 +8226,12 @@ def test_delete_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_product_set in client._transport._wrapped_methods - ) + assert client._transport.delete_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_set] = mock_rpc request = {} client.delete_product_set(request) @@ -9188,85 +8246,80 @@ def test_delete_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_product_set_rest_required_fields( - request_type=product_search_service.DeleteProductSetRequest, -): +def test_delete_product_set_rest_required_fields(request_type=product_search_service.DeleteProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_product_set_rest_flattened(): @@ -9276,26 +8329,24 @@ def test_delete_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9305,14 +8356,10 @@ def test_delete_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_delete_product_set_rest_flattened_error(transport: str = "rest"): +def test_delete_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9323,7 +8370,7 @@ def test_delete_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) @@ -9345,9 +8392,7 @@ def test_create_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.create_product] = mock_rpc request = {} @@ -9363,64 +8408,59 @@ def test_create_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_product_rest_required_fields( - request_type=product_search_service.CreateProductRequest, -): +def test_create_product_rest_required_fields(request_type=product_search_service.CreateProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("product_id",)) + assert not set(unset_fields) - set(("product_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9430,32 +8470,24 @@ def test_create_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_product._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("productId",)) - & set( - ( - "parent", - "product", - ) - ) - ) + assert set(unset_fields) == (set(("productId", )) & set(("parent", "product", ))) def test_create_product_rest_flattened(): @@ -9465,18 +8497,18 @@ def test_create_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) mock_args.update(sample_request) @@ -9486,7 +8518,7 @@ def test_create_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9496,14 +8528,10 @@ def test_create_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*}/products" % client.transport._host, args[1]) -def test_create_product_rest_flattened_error(transport: str = "rest"): +def test_create_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9514,9 +8542,9 @@ def test_create_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) @@ -9538,9 +8566,7 @@ def test_list_products_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} @@ -9556,67 +8582,57 @@ def test_list_products_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_products_rest_required_fields( - request_type=product_search_service.ListProductsRequest, -): +def test_list_products_rest_required_fields(request_type=product_search_service.ListProductsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -9627,32 +8643,24 @@ def test_list_products_rest_required_fields( return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_products_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_products._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_products_rest_flattened(): @@ -9662,16 +8670,16 @@ def test_list_products_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -9681,7 +8689,7 @@ def test_list_products_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9691,14 +8699,10 @@ def test_list_products_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*}/products" % client.transport._host, args[1]) -def test_list_products_rest_flattened_error(transport: str = "rest"): +def test_list_products_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9709,20 +8713,20 @@ def test_list_products_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_products_rest_pager(transport: str = "rest"): +def test_list_products_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductsResponse( @@ -9731,17 +8735,17 @@ def test_list_products_rest_pager(transport: str = "rest"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -9754,25 +8758,24 @@ def test_list_products_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductsResponse.to_json(x) for x in response - ) + response = tuple(product_search_service.ListProductsResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} pager = client.list_products(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) + assert all(isinstance(i, product_search_service.Product) + for i in results) pages = list(client.list_products(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -9794,9 +8797,7 @@ def test_get_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product] = mock_rpc request = {} @@ -9812,60 +8813,55 @@ def test_get_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_product_rest_required_fields( - request_type=product_search_service.GetProductRequest, -): +def test_get_product_rest_required_fields(request_type=product_search_service.GetProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -9876,24 +8872,24 @@ def test_get_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_product_rest_flattened(): @@ -9903,16 +8899,16 @@ def test_get_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/products/sample3"} + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -9922,7 +8918,7 @@ def test_get_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9932,14 +8928,10 @@ def test_get_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_get_product_rest_flattened_error(transport: str = "rest"): +def test_get_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9950,7 +8942,7 @@ def test_get_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) @@ -9972,9 +8964,7 @@ def test_update_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} @@ -9990,59 +8980,54 @@ def test_update_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_product_rest_required_fields( - request_type=product_search_service.UpdateProductRequest, -): +def test_update_product_rest_required_fields(request_type=product_search_service.UpdateProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("update_mask", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10052,24 +9037,24 @@ def test_update_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_update_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.update_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("product",))) + assert set(unset_fields) == (set(("updateMask", )) & set(("product", ))) def test_update_product_rest_flattened(): @@ -10079,19 +9064,17 @@ def test_update_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } + sample_request = {'product': {'name': 'projects/sample1/locations/sample2/products/sample3'}} # get truthy value for each flattened field mock_args = dict( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) mock_args.update(sample_request) @@ -10101,7 +9084,7 @@ def test_update_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10111,14 +9094,10 @@ def test_update_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{product.name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{product.name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_update_product_rest_flattened_error(transport: str = "rest"): +def test_update_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10129,8 +9108,8 @@ def test_update_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) @@ -10152,9 +9131,7 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc request = {} @@ -10170,85 +9147,80 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_product_rest_required_fields( - request_type=product_search_service.DeleteProductRequest, -): +def test_delete_product_rest_required_fields(request_type=product_search_service.DeleteProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_product_rest_flattened(): @@ -10258,24 +9230,24 @@ def test_delete_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/products/sample3"} + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10285,14 +9257,10 @@ def test_delete_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_delete_product_rest_flattened_error(transport: str = "rest"): +def test_delete_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10303,7 +9271,7 @@ def test_delete_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) @@ -10321,19 +9289,12 @@ def test_create_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.create_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_reference_image] = mock_rpc request = {} client.create_reference_image(request) @@ -10348,64 +9309,59 @@ def test_create_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_reference_image_rest_required_fields( - request_type=product_search_service.CreateReferenceImageRequest, -): +def test_create_reference_image_rest_required_fields(request_type=product_search_service.CreateReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reference_image._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reference_image._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("reference_image_id",)) + assert not set(unset_fields) - set(("reference_image_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10415,32 +9371,24 @@ def test_create_reference_image_rest_required_fields( return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("referenceImageId",)) - & set( - ( - "parent", - "referenceImage", - ) - ) - ) + assert set(unset_fields) == (set(("referenceImageId", )) & set(("parent", "referenceImage", ))) def test_create_reference_image_rest_flattened(): @@ -10450,20 +9398,18 @@ def test_create_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) mock_args.update(sample_request) @@ -10473,7 +9419,7 @@ def test_create_reference_image_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10483,14 +9429,10 @@ def test_create_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" % client.transport._host, args[1]) -def test_create_reference_image_rest_flattened_error(transport: str = "rest"): +def test_create_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10501,9 +9443,9 @@ def test_create_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) @@ -10521,19 +9463,12 @@ def test_delete_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.delete_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_reference_image] = mock_rpc request = {} client.delete_reference_image(request) @@ -10548,85 +9483,80 @@ def test_delete_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_reference_image_rest_required_fields( - request_type=product_search_service.DeleteReferenceImageRequest, -): +def test_delete_reference_image_rest_required_fields(request_type=product_search_service.DeleteReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_reference_image_rest_flattened(): @@ -10636,26 +9566,24 @@ def test_delete_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/sample4'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10665,14 +9593,10 @@ def test_delete_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" % client.transport._host, args[1]) -def test_delete_reference_image_rest_flattened_error(transport: str = "rest"): +def test_delete_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10683,7 +9607,7 @@ def test_delete_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) @@ -10701,19 +9625,12 @@ def test_list_reference_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_reference_images - in client._transport._wrapped_methods - ) + assert client._transport.list_reference_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reference_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_reference_images] = mock_rpc request = {} client.list_reference_images(request) @@ -10728,67 +9645,57 @@ def test_list_reference_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_reference_images_rest_required_fields( - request_type=product_search_service.ListReferenceImagesRequest, -): +def test_list_reference_images_rest_required_fields(request_type=product_search_service.ListReferenceImagesRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reference_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reference_images._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reference_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reference_images._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -10796,37 +9703,27 @@ def test_list_reference_images_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_reference_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_reference_images_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_reference_images._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_reference_images_rest_flattened(): @@ -10836,18 +9733,16 @@ def test_list_reference_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -10855,11 +9750,9 @@ def test_list_reference_images_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10869,14 +9762,10 @@ def test_list_reference_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" % client.transport._host, args[1]) -def test_list_reference_images_rest_flattened_error(transport: str = "rest"): +def test_list_reference_images_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10887,20 +9776,20 @@ def test_list_reference_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_reference_images_rest_pager(transport: str = "rest"): +def test_list_reference_images_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListReferenceImagesResponse( @@ -10909,17 +9798,17 @@ def test_list_reference_images_rest_pager(transport: str = "rest"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -10932,30 +9821,24 @@ def test_list_reference_images_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListReferenceImagesResponse.to_json(x) - for x in response - ) + response = tuple(product_search_service.ListReferenceImagesResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} pager = client.list_reference_images(request=sample_request) results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in results - ) + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in results) pages = list(client.list_reference_images(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -10973,18 +9856,12 @@ def test_get_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_reference_image in client._transport._wrapped_methods - ) + assert client._transport.get_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_reference_image] = mock_rpc request = {} client.get_reference_image(request) @@ -10999,60 +9876,55 @@ def test_get_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_reference_image_rest_required_fields( - request_type=product_search_service.GetReferenceImageRequest, -): +def test_get_reference_image_rest_required_fields(request_type=product_search_service.GetReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11063,24 +9935,24 @@ def test_get_reference_image_rest_required_fields( return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_reference_image_rest_flattened(): @@ -11090,18 +9962,16 @@ def test_get_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/sample4'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -11111,7 +9981,7 @@ def test_get_reference_image_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11121,14 +9991,10 @@ def test_get_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" % client.transport._host, args[1]) -def test_get_reference_image_rest_flattened_error(transport: str = "rest"): +def test_get_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11139,7 +10005,7 @@ def test_get_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) @@ -11157,19 +10023,12 @@ def test_add_product_to_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.add_product_to_product_set - in client._transport._wrapped_methods - ) + assert client._transport.add_product_to_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_product_to_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_product_to_product_set] = mock_rpc request = {} client.add_product_to_product_set(request) @@ -11184,9 +10043,7 @@ def test_add_product_to_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_add_product_to_product_set_rest_required_fields( - request_type=product_search_service.AddProductToProductSetRequest, -): +def test_add_product_to_product_set_rest_required_fields(request_type=product_search_service.AddProductToProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} @@ -11194,88 +10051,77 @@ def test_add_product_to_product_set_rest_required_fields( request_init["product"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_product_to_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_product_to_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["product"] = "product_value" + jsonified_request["name"] = 'name_value' + jsonified_request["product"] = 'product_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_product_to_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_product_to_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" + assert jsonified_request["product"] == 'product_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_product_to_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_add_product_to_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.add_product_to_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "product", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "product", ))) def test_add_product_to_product_set_rest_flattened(): @@ -11285,27 +10131,25 @@ def test_add_product_to_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11315,14 +10159,10 @@ def test_add_product_to_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct" % client.transport._host, args[1]) -def test_add_product_to_product_set_rest_flattened_error(transport: str = "rest"): +def test_add_product_to_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11333,8 +10173,8 @@ def test_add_product_to_product_set_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) @@ -11352,19 +10192,12 @@ def test_remove_product_from_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.remove_product_from_product_set - in client._transport._wrapped_methods - ) + assert client._transport.remove_product_from_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_product_from_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_product_from_product_set] = mock_rpc request = {} client.remove_product_from_product_set(request) @@ -11379,9 +10212,7 @@ def test_remove_product_from_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_remove_product_from_product_set_rest_required_fields( - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +def test_remove_product_from_product_set_rest_required_fields(request_type=product_search_service.RemoveProductFromProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} @@ -11389,90 +10220,77 @@ def test_remove_product_from_product_set_rest_required_fields( request_init["product"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_product_from_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_product_from_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["product"] = "product_value" + jsonified_request["name"] = 'name_value' + jsonified_request["product"] = 'product_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_product_from_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_product_from_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" + assert jsonified_request["product"] == 'product_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_product_from_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_remove_product_from_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) - unset_fields = transport.remove_product_from_product_set._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "product", - ) - ) - ) + unset_fields = transport.remove_product_from_product_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "product", ))) def test_remove_product_from_product_set_rest_flattened(): @@ -11482,27 +10300,25 @@ def test_remove_product_from_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11512,14 +10328,10 @@ def test_remove_product_from_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" % client.transport._host, args[1]) -def test_remove_product_from_product_set_rest_flattened_error(transport: str = "rest"): +def test_remove_product_from_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11530,8 +10342,8 @@ def test_remove_product_from_product_set_rest_flattened_error(transport: str = " with pytest.raises(ValueError): client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) @@ -11549,19 +10361,12 @@ def test_list_products_in_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_products_in_product_set - in client._transport._wrapped_methods - ) + assert client._transport.list_products_in_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_products_in_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products_in_product_set] = mock_rpc request = {} client.list_products_in_product_set(request) @@ -11576,67 +10381,57 @@ def test_list_products_in_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_products_in_product_set_rest_required_fields( - request_type=product_search_service.ListProductsInProductSetRequest, -): +def test_list_products_in_product_set_rest_required_fields(request_type=product_search_service.ListProductsInProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products_in_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products_in_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products_in_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products_in_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("page_size", "page_token", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11644,37 +10439,27 @@ def test_list_products_in_product_set_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products_in_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_products_in_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_products_in_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("name",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) def test_list_products_in_product_set_rest_flattened(): @@ -11684,18 +10469,16 @@ def test_list_products_in_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -11703,11 +10486,9 @@ def test_list_products_in_product_set_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11717,14 +10498,10 @@ def test_list_products_in_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products" % client.transport._host, args[1]) -def test_list_products_in_product_set_rest_flattened_error(transport: str = "rest"): +def test_list_products_in_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11735,20 +10512,20 @@ def test_list_products_in_product_set_rest_flattened_error(transport: str = "res with pytest.raises(ValueError): client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) -def test_list_products_in_product_set_rest_pager(transport: str = "rest"): +def test_list_products_in_product_set_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductsInProductSetResponse( @@ -11757,17 +10534,17 @@ def test_list_products_in_product_set_rest_pager(transport: str = "rest"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -11780,28 +10557,24 @@ def test_list_products_in_product_set_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductsInProductSetResponse.to_json(x) - for x in response - ) + response = tuple(product_search_service.ListProductsInProductSetResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} pager = client.list_products_in_product_set(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) + assert all(isinstance(i, product_search_service.Product) + for i in results) pages = list(client.list_products_in_product_set(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -11819,18 +10592,12 @@ def test_import_product_sets_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.import_product_sets in client._transport._wrapped_methods - ) + assert client._transport.import_product_sets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_product_sets] = mock_rpc request = {} client.import_product_sets(request) @@ -11849,94 +10616,81 @@ def test_import_product_sets_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_import_product_sets_rest_required_fields( - request_type=product_search_service.ImportProductSetsRequest, -): +def test_import_product_sets_rest_required_fields(request_type=product_search_service.ImportProductSetsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_product_sets._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_product_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.import_product_sets(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_import_product_sets_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.import_product_sets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("parent", "inputConfig", ))) def test_import_product_sets_rest_flattened(): @@ -11946,21 +10700,17 @@ def test_import_product_sets_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) mock_args.update(sample_request) @@ -11968,7 +10718,7 @@ def test_import_product_sets_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11978,14 +10728,10 @@ def test_import_product_sets_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p3beta1/{parent=projects/*/locations/*}/productSets:import" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p3beta1/{parent=projects/*/locations/*}/productSets:import" % client.transport._host, args[1]) -def test_import_product_sets_rest_flattened_error(transport: str = "rest"): +def test_import_product_sets_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11996,12 +10742,8 @@ def test_import_product_sets_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) @@ -12043,7 +10785,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ProductSearchClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -12065,7 +10808,6 @@ def test_transport_instance(): client = ProductSearchClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( @@ -12080,23 +10822,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - transports.ProductSearchRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + transports.ProductSearchRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ProductSearchClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -12106,7 +10843,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -12121,8 +10859,8 @@ def test_create_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.create_product_set(request=None) @@ -12144,8 +10882,8 @@ def test_list_product_sets_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: call.return_value = product_search_service.ListProductSetsResponse() client.list_product_sets(request=None) @@ -12166,7 +10904,9 @@ def test_get_product_set_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.get_product_set(request=None) @@ -12188,8 +10928,8 @@ def test_update_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.update_product_set(request=None) @@ -12211,8 +10951,8 @@ def test_delete_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = None client.delete_product_set(request=None) @@ -12233,7 +10973,9 @@ def test_create_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: call.return_value = product_search_service.Product() client.create_product(request=None) @@ -12254,7 +10996,9 @@ def test_list_products_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: call.return_value = product_search_service.ListProductsResponse() client.list_products(request=None) @@ -12275,7 +11019,9 @@ def test_get_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: call.return_value = product_search_service.Product() client.get_product(request=None) @@ -12296,7 +11042,9 @@ def test_update_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: call.return_value = product_search_service.Product() client.update_product(request=None) @@ -12317,7 +11065,9 @@ def test_delete_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = None client.delete_product(request=None) @@ -12339,8 +11089,8 @@ def test_create_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.create_reference_image(request=None) @@ -12362,8 +11112,8 @@ def test_delete_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = None client.delete_reference_image(request=None) @@ -12385,8 +11135,8 @@ def test_list_reference_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: call.return_value = product_search_service.ListReferenceImagesResponse() client.list_reference_images(request=None) @@ -12408,8 +11158,8 @@ def test_get_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.get_reference_image(request=None) @@ -12431,8 +11181,8 @@ def test_add_product_to_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = None client.add_product_to_product_set(request=None) @@ -12454,8 +11204,8 @@ def test_remove_product_from_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = None client.remove_product_from_product_set(request=None) @@ -12477,8 +11227,8 @@ def test_list_products_in_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: call.return_value = product_search_service.ListProductsInProductSetResponse() client.list_products_in_product_set(request=None) @@ -12500,9 +11250,9 @@ def test_import_product_sets_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.import_product_sets(request=None) # Establish that the underlying stub method was called. @@ -12522,7 +11272,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -12538,15 +11289,13 @@ async def test_create_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.create_product_set(request=None) # Establish that the underlying stub method was called. @@ -12568,14 +11317,12 @@ async def test_list_product_sets_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse( + next_page_token='next_page_token_value', + )) await client.list_product_sets(request=None) # Establish that the underlying stub method was called. @@ -12596,14 +11343,14 @@ async def test_get_product_set_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.get_product_set(request=None) # Establish that the underlying stub method was called. @@ -12625,15 +11372,13 @@ async def test_update_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.update_product_set(request=None) # Establish that the underlying stub method was called. @@ -12655,8 +11400,8 @@ async def test_delete_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product_set(request=None) @@ -12679,16 +11424,16 @@ async def test_create_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.create_product(request=None) # Establish that the underlying stub method was called. @@ -12709,13 +11454,13 @@ async def test_list_products_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) await client.list_products(request=None) # Establish that the underlying stub method was called. @@ -12736,16 +11481,16 @@ async def test_get_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.get_product(request=None) # Establish that the underlying stub method was called. @@ -12766,16 +11511,16 @@ async def test_update_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.update_product(request=None) # Establish that the underlying stub method was called. @@ -12796,7 +11541,9 @@ async def test_delete_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product(request=None) @@ -12820,15 +11567,13 @@ async def test_create_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) await client.create_reference_image(request=None) # Establish that the underlying stub method was called. @@ -12850,8 +11595,8 @@ async def test_delete_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_reference_image(request=None) @@ -12875,15 +11620,13 @@ async def test_list_reference_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse( + page_size=951, + next_page_token='next_page_token_value', + )) await client.list_reference_images(request=None) # Establish that the underlying stub method was called. @@ -12905,15 +11648,13 @@ async def test_get_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) await client.get_reference_image(request=None) # Establish that the underlying stub method was called. @@ -12935,8 +11676,8 @@ async def test_add_product_to_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.add_product_to_product_set(request=None) @@ -12960,8 +11701,8 @@ async def test_remove_product_from_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.remove_product_from_product_set(request=None) @@ -12985,14 +11726,12 @@ async def test_list_products_in_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse( + next_page_token='next_page_token_value', + )) await client.list_products_in_product_set(request=None) # Establish that the underlying stub method was called. @@ -13014,11 +11753,11 @@ async def test_import_product_sets_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.import_product_sets(request=None) @@ -13037,23 +11776,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_create_product_set_rest_bad_request( - request_type=product_search_service.CreateProductSetRequest, -): +def test_create_product_set_rest_bad_request(request_type=product_search_service.CreateProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13062,43 +11798,25 @@ def test_create_product_set_rest_bad_request( client.create_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductSetRequest, + dict, +]) def test_create_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["product_set"] = { - "name": "name_value", - "display_name": "display_name_value", - "index_time": {"seconds": 751, "nanos": 543}, - "index_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["product_set"] = {'name': 'name_value', 'display_name': 'display_name_value', 'index_time': {'seconds': 751, 'nanos': 543}, 'index_error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.CreateProductSetRequest.meta.fields[ - "product_set" - ] + test_field = product_search_service.CreateProductSetRequest.meta.fields["product_set"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13112,7 +11830,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -13126,7 +11844,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product_set"].items(): # pragma: NO COVER + for field, value in request_init["product_set"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13141,16 +11859,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -13163,11 +11877,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13177,44 +11891,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_create_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateProductSetRequest.pb( - product_search_service.CreateProductSetRequest() - ) + pb_message = product_search_service.CreateProductSetRequest.pb(product_search_service.CreateProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13225,13 +11929,11 @@ def test_create_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.CreateProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -13239,36 +11941,27 @@ def test_create_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.create_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_product_sets_rest_bad_request( - request_type=product_search_service.ListProductSetsRequest, -): +def test_list_product_sets_rest_bad_request(request_type=product_search_service.ListProductSetsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13277,27 +11970,25 @@ def test_list_product_sets_rest_bad_request( client.list_product_sets(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductSetsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductSetsRequest, + dict, +]) def test_list_product_sets_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -13307,43 +11998,33 @@ def test_list_product_sets_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_product_sets(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_product_sets_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_product_sets" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_list_product_sets_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_product_sets" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_product_sets") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_product_sets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_product_sets") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductSetsRequest.pb( - product_search_service.ListProductSetsRequest() - ) + pb_message = product_search_service.ListProductSetsRequest.pb(product_search_service.ListProductSetsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13354,53 +12035,39 @@ def test_list_product_sets_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductSetsResponse.to_json( - product_search_service.ListProductSetsResponse() - ) + return_value = product_search_service.ListProductSetsResponse.to_json(product_search_service.ListProductSetsResponse()) req.return_value.content = return_value request = product_search_service.ListProductSetsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductSetsResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductSetsResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductSetsResponse(), metadata - client.list_product_sets( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_product_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_product_set_rest_bad_request( - request_type=product_search_service.GetProductSetRequest, -): +def test_get_product_set_rest_bad_request(request_type=product_search_service.GetProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13409,28 +12076,26 @@ def test_get_product_set_rest_bad_request( client.get_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductSetRequest, + dict, +]) def test_get_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13440,44 +12105,34 @@ def test_get_product_set_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_get_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetProductSetRequest.pb( - product_search_service.GetProductSetRequest() - ) + pb_message = product_search_service.GetProductSetRequest.pb(product_search_service.GetProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13488,13 +12143,11 @@ def test_get_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.GetProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -13502,40 +12155,27 @@ def test_get_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.get_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_product_set_rest_bad_request( - request_type=product_search_service.UpdateProductSetRequest, -): +def test_update_product_set_rest_bad_request(request_type=product_search_service.UpdateProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } + request_init = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13544,47 +12184,25 @@ def test_update_product_set_rest_bad_request( client.update_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductSetRequest, + dict, +]) def test_update_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } - request_init["product_set"] = { - "name": "projects/sample1/locations/sample2/productSets/sample3", - "display_name": "display_name_value", - "index_time": {"seconds": 751, "nanos": 543}, - "index_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - } + request_init = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/sample3'}} + request_init["product_set"] = {'name': 'projects/sample1/locations/sample2/productSets/sample3', 'display_name': 'display_name_value', 'index_time': {'seconds': 751, 'nanos': 543}, 'index_error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.UpdateProductSetRequest.meta.fields[ - "product_set" - ] + test_field = product_search_service.UpdateProductSetRequest.meta.fields["product_set"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13598,7 +12216,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -13612,7 +12230,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product_set"].items(): # pragma: NO COVER + for field, value in request_init["product_set"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13627,16 +12245,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -13649,11 +12263,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13663,44 +12277,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_update_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_update_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_update_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_update_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.UpdateProductSetRequest.pb( - product_search_service.UpdateProductSetRequest() - ) + pb_message = product_search_service.UpdateProductSetRequest.pb(product_search_service.UpdateProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13711,13 +12315,11 @@ def test_update_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.UpdateProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -13725,36 +12327,27 @@ def test_update_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.update_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_product_set_rest_bad_request( - request_type=product_search_service.DeleteProductSetRequest, -): +def test_delete_product_set_rest_bad_request(request_type=product_search_service.DeleteProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13763,32 +12356,30 @@ def test_delete_product_set_rest_bad_request( client.delete_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductSetRequest, + dict, +]) def test_delete_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product_set(request) @@ -13801,23 +12392,15 @@ def test_delete_product_set_rest_call_success(request_type): def test_delete_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteProductSetRequest.pb( - product_search_service.DeleteProductSetRequest() - ) + pb_message = product_search_service.DeleteProductSetRequest.pb(product_search_service.DeleteProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13830,40 +12413,31 @@ def test_delete_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_create_product_rest_bad_request( - request_type=product_search_service.CreateProductRequest, -): +def test_create_product_rest_bad_request(request_type=product_search_service.CreateProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13872,27 +12446,19 @@ def test_create_product_rest_bad_request( client.create_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductRequest, + dict, +]) def test_create_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["product"] = { - "name": "name_value", - "display_name": "display_name_value", - "description": "description_value", - "product_category": "product_category_value", - "product_labels": [{"key": "key_value", "value": "value_value"}], - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["product"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'product_category': 'product_category_value', 'product_labels': [{'key': 'key_value', 'value': 'value_value'}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -13912,7 +12478,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -13926,7 +12492,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER + for field, value in request_init["product"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13941,16 +12507,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -13963,13 +12525,13 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -13979,46 +12541,36 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_create_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateProductRequest.pb( - product_search_service.CreateProductRequest() - ) + pb_message = product_search_service.CreateProductRequest.pb(product_search_service.CreateProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14029,13 +12581,11 @@ def test_create_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.CreateProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14043,36 +12593,27 @@ def test_create_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.create_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_products_rest_bad_request( - request_type=product_search_service.ListProductsRequest, -): +def test_list_products_rest_bad_request(request_type=product_search_service.ListProductsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14081,27 +12622,25 @@ def test_list_products_rest_bad_request( client.list_products(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsRequest, + dict, +]) def test_list_products_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -14111,43 +12650,33 @@ def test_list_products_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_products_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_products" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_list_products_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_products" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_products") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductsRequest.pb( - product_search_service.ListProductsRequest() - ) + pb_message = product_search_service.ListProductsRequest.pb(product_search_service.ListProductsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14158,53 +12687,39 @@ def test_list_products_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductsResponse.to_json( - product_search_service.ListProductsResponse() - ) + return_value = product_search_service.ListProductsResponse.to_json(product_search_service.ListProductsResponse()) req.return_value.content = return_value request = product_search_service.ListProductsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductsResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductsResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductsResponse(), metadata - client.list_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_product_rest_bad_request( - request_type=product_search_service.GetProductRequest, -): +def test_get_product_rest_bad_request(request_type=product_search_service.GetProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14213,30 +12728,28 @@ def test_get_product_rest_bad_request( client.get_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductRequest, + dict, +]) def test_get_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -14246,46 +12759,36 @@ def test_get_product_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_get_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetProductRequest.pb( - product_search_service.GetProductRequest() - ) + pb_message = product_search_service.GetProductRequest.pb(product_search_service.GetProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14296,13 +12799,11 @@ def test_get_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.GetProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14310,38 +12811,27 @@ def test_get_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.get_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_product_rest_bad_request( - request_type=product_search_service.UpdateProductRequest, -): +def test_update_product_rest_bad_request(request_type=product_search_service.UpdateProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } + request_init = {'product': {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14350,29 +12840,19 @@ def test_update_product_rest_bad_request( client.update_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductRequest, + dict, +]) def test_update_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } - request_init["product"] = { - "name": "projects/sample1/locations/sample2/products/sample3", - "display_name": "display_name_value", - "description": "description_value", - "product_category": "product_category_value", - "product_labels": [{"key": "key_value", "value": "value_value"}], - } + request_init = {'product': {'name': 'projects/sample1/locations/sample2/products/sample3'}} + request_init["product"] = {'name': 'projects/sample1/locations/sample2/products/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'product_category': 'product_category_value', 'product_labels': [{'key': 'key_value', 'value': 'value_value'}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -14392,7 +12872,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14406,7 +12886,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER + for field, value in request_init["product"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14421,16 +12901,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14443,13 +12919,13 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -14459,46 +12935,36 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_update_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_update_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_update_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_update_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.UpdateProductRequest.pb( - product_search_service.UpdateProductRequest() - ) + pb_message = product_search_service.UpdateProductRequest.pb(product_search_service.UpdateProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14509,13 +12975,11 @@ def test_update_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.UpdateProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14523,36 +12987,27 @@ def test_update_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.update_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_product_rest_bad_request( - request_type=product_search_service.DeleteProductRequest, -): +def test_delete_product_rest_bad_request(request_type=product_search_service.DeleteProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14561,32 +13016,30 @@ def test_delete_product_rest_bad_request( client.delete_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductRequest, + dict, +]) def test_delete_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product(request) @@ -14599,23 +13052,15 @@ def test_delete_product_rest_call_success(request_type): def test_delete_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_product") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteProductRequest.pb( - product_search_service.DeleteProductRequest() - ) + pb_message = product_search_service.DeleteProductRequest.pb(product_search_service.DeleteProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14628,40 +13073,31 @@ def test_delete_product_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_create_reference_image_rest_bad_request( - request_type=product_search_service.CreateReferenceImageRequest, -): +def test_create_reference_image_rest_bad_request(request_type=product_search_service.CreateReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14670,38 +13106,25 @@ def test_create_reference_image_rest_bad_request( client.create_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateReferenceImageRequest, + dict, +]) def test_create_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} - request_init["reference_image"] = { - "name": "name_value", - "uri": "uri_value", - "bounding_polys": [ - { - "vertices": [{"x": 120, "y": 121}], - "normalized_vertices": [{"x": 0.12, "y": 0.121}], - } - ], - } + request_init = {'parent': 'projects/sample1/locations/sample2/products/sample3'} + request_init["reference_image"] = {'name': 'name_value', 'uri': 'uri_value', 'bounding_polys': [{'vertices': [{'x': 120, 'y': 121}], 'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.CreateReferenceImageRequest.meta.fields[ - "reference_image" - ] + test_field = product_search_service.CreateReferenceImageRequest.meta.fields["reference_image"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -14715,7 +13138,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14729,7 +13152,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["reference_image"].items(): # pragma: NO COVER + for field, value in request_init["reference_image"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14744,16 +13167,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14766,11 +13185,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) # Wrap the value into a proper Response obj @@ -14780,45 +13199,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_reference_image(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_reference_image" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_create_reference_image_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_reference_image") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_reference_image_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_reference_image") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateReferenceImageRequest.pb( - product_search_service.CreateReferenceImageRequest() - ) + pb_message = product_search_service.CreateReferenceImageRequest.pb(product_search_service.CreateReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14829,55 +13237,39 @@ def test_create_reference_image_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ReferenceImage.to_json( - product_search_service.ReferenceImage() - ) + return_value = product_search_service.ReferenceImage.to_json(product_search_service.ReferenceImage()) req.return_value.content = return_value request = product_search_service.CreateReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ReferenceImage() - post_with_metadata.return_value = ( - product_search_service.ReferenceImage(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ReferenceImage(), metadata - client.create_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_reference_image_rest_bad_request( - request_type=product_search_service.DeleteReferenceImageRequest, -): +def test_delete_reference_image_rest_bad_request(request_type=product_search_service.DeleteReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14886,34 +13278,30 @@ def test_delete_reference_image_rest_bad_request( client.delete_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteReferenceImageRequest, + dict, +]) def test_delete_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_reference_image(request) @@ -14926,23 +13314,15 @@ def test_delete_reference_image_rest_call_success(request_type): def test_delete_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_reference_image") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteReferenceImageRequest.pb( - product_search_service.DeleteReferenceImageRequest() - ) + pb_message = product_search_service.DeleteReferenceImageRequest.pb(product_search_service.DeleteReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14955,40 +13335,31 @@ def test_delete_reference_image_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_list_reference_images_rest_bad_request( - request_type=product_search_service.ListReferenceImagesRequest, -): +def test_list_reference_images_rest_bad_request(request_type=product_search_service.ListReferenceImagesRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14997,28 +13368,26 @@ def test_list_reference_images_rest_bad_request( client.list_reference_images(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListReferenceImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListReferenceImagesRequest, + dict, +]) def test_list_reference_images_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", + page_size=951, + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -15026,11 +13395,9 @@ def test_list_reference_images_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_reference_images(request) @@ -15038,37 +13405,26 @@ def test_list_reference_images_rest_call_success(request_type): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_reference_images_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_reference_images" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_list_reference_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_reference_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_reference_images") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_reference_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_reference_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListReferenceImagesRequest.pb( - product_search_service.ListReferenceImagesRequest() - ) + pb_message = product_search_service.ListReferenceImagesRequest.pb(product_search_service.ListReferenceImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15079,55 +13435,39 @@ def test_list_reference_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListReferenceImagesResponse.to_json( - product_search_service.ListReferenceImagesResponse() - ) + return_value = product_search_service.ListReferenceImagesResponse.to_json(product_search_service.ListReferenceImagesResponse()) req.return_value.content = return_value request = product_search_service.ListReferenceImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListReferenceImagesResponse() - post_with_metadata.return_value = ( - product_search_service.ListReferenceImagesResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListReferenceImagesResponse(), metadata - client.list_reference_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_reference_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_reference_image_rest_bad_request( - request_type=product_search_service.GetReferenceImageRequest, -): +def test_get_reference_image_rest_bad_request(request_type=product_search_service.GetReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15136,30 +13476,26 @@ def test_get_reference_image_rest_bad_request( client.get_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetReferenceImageRequest, + dict, +]) def test_get_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) # Wrap the value into a proper Response obj @@ -15169,45 +13505,34 @@ def test_get_reference_image_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_reference_image(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_reference_image" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_get_reference_image_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_reference_image") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_reference_image_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_reference_image") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetReferenceImageRequest.pb( - product_search_service.GetReferenceImageRequest() - ) + pb_message = product_search_service.GetReferenceImageRequest.pb(product_search_service.GetReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15218,53 +13543,39 @@ def test_get_reference_image_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ReferenceImage.to_json( - product_search_service.ReferenceImage() - ) + return_value = product_search_service.ReferenceImage.to_json(product_search_service.ReferenceImage()) req.return_value.content = return_value request = product_search_service.GetReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ReferenceImage() - post_with_metadata.return_value = ( - product_search_service.ReferenceImage(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ReferenceImage(), metadata - client.get_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_add_product_to_product_set_rest_bad_request( - request_type=product_search_service.AddProductToProductSetRequest, -): +def test_add_product_to_product_set_rest_bad_request(request_type=product_search_service.AddProductToProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15273,32 +13584,30 @@ def test_add_product_to_product_set_rest_bad_request( client.add_product_to_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.AddProductToProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.AddProductToProductSetRequest, + dict, +]) def test_add_product_to_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_product_to_product_set(request) @@ -15311,23 +13620,15 @@ def test_add_product_to_product_set_rest_call_success(request_type): def test_add_product_to_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_add_product_to_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_add_product_to_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.AddProductToProductSetRequest.pb( - product_search_service.AddProductToProductSetRequest() - ) + pb_message = product_search_service.AddProductToProductSetRequest.pb(product_search_service.AddProductToProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15340,40 +13641,31 @@ def test_add_product_to_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.AddProductToProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.add_product_to_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.add_product_to_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_remove_product_from_product_set_rest_bad_request( - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +def test_remove_product_from_product_set_rest_bad_request(request_type=product_search_service.RemoveProductFromProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15382,32 +13674,30 @@ def test_remove_product_from_product_set_rest_bad_request( client.remove_product_from_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.RemoveProductFromProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.RemoveProductFromProductSetRequest, + dict, +]) def test_remove_product_from_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_product_from_product_set(request) @@ -15420,23 +13710,15 @@ def test_remove_product_from_product_set_rest_call_success(request_type): def test_remove_product_from_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_remove_product_from_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_remove_product_from_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.RemoveProductFromProductSetRequest.pb( - product_search_service.RemoveProductFromProductSetRequest() - ) + pb_message = product_search_service.RemoveProductFromProductSetRequest.pb(product_search_service.RemoveProductFromProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15449,40 +13731,31 @@ def test_remove_product_from_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.RemoveProductFromProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.remove_product_from_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.remove_product_from_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_list_products_in_product_set_rest_bad_request( - request_type=product_search_service.ListProductsInProductSetRequest, -): +def test_list_products_in_product_set_rest_bad_request(request_type=product_search_service.ListProductsInProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15491,27 +13764,25 @@ def test_list_products_in_product_set_rest_bad_request( client.list_products_in_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsInProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsInProductSetRequest, + dict, +]) def test_list_products_in_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -15519,48 +13790,35 @@ def test_list_products_in_product_set_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products_in_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_products_in_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_products_in_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_list_products_in_product_set_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_products_in_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_in_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_in_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_products_in_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductsInProductSetRequest.pb( - product_search_service.ListProductsInProductSetRequest() - ) + pb_message = product_search_service.ListProductsInProductSetRequest.pb(product_search_service.ListProductsInProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15571,53 +13829,39 @@ def test_list_products_in_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductsInProductSetResponse.to_json( - product_search_service.ListProductsInProductSetResponse() - ) + return_value = product_search_service.ListProductsInProductSetResponse.to_json(product_search_service.ListProductsInProductSetResponse()) req.return_value.content = return_value request = product_search_service.ListProductsInProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductsInProductSetResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductsInProductSetResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductsInProductSetResponse(), metadata - client.list_products_in_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_products_in_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_import_product_sets_rest_bad_request( - request_type=product_search_service.ImportProductSetsRequest, -): +def test_import_product_sets_rest_bad_request(request_type=product_search_service.ImportProductSetsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15626,32 +13870,30 @@ def test_import_product_sets_rest_bad_request( client.import_product_sets(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ImportProductSetsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ImportProductSetsRequest, + dict, +]) def test_import_product_sets_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.import_product_sets(request) @@ -15664,32 +13906,20 @@ def test_import_product_sets_rest_call_success(request_type): def test_import_product_sets_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_import_product_sets" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_import_product_sets_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_import_product_sets" - ) as pre: + 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.ProductSearchRestInterceptor, "post_import_product_sets") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_import_product_sets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_import_product_sets") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ImportProductSetsRequest.pb( - product_search_service.ImportProductSetsRequest() - ) + pb_message = product_search_service.ImportProductSetsRequest.pb(product_search_service.ImportProductSetsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15704,7 +13934,7 @@ def test_import_product_sets_rest_interceptors(null_interceptor): req.return_value.content = return_value request = product_search_service.ImportProductSetsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -15712,22 +13942,16 @@ def test_import_product_sets_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.import_product_sets( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.import_product_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -15742,8 +13966,8 @@ def test_create_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: client.create_product_set(request=None) # Establish that the underlying stub method was called. @@ -15764,8 +13988,8 @@ def test_list_product_sets_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: client.list_product_sets(request=None) # Establish that the underlying stub method was called. @@ -15785,7 +14009,9 @@ def test_get_product_set_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: client.get_product_set(request=None) # Establish that the underlying stub method was called. @@ -15806,8 +14032,8 @@ def test_update_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: client.update_product_set(request=None) # Establish that the underlying stub method was called. @@ -15828,8 +14054,8 @@ def test_delete_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: client.delete_product_set(request=None) # Establish that the underlying stub method was called. @@ -15849,7 +14075,9 @@ def test_create_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: client.create_product(request=None) # Establish that the underlying stub method was called. @@ -15869,7 +14097,9 @@ def test_list_products_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: client.list_products(request=None) # Establish that the underlying stub method was called. @@ -15889,7 +14119,9 @@ def test_get_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: client.get_product(request=None) # Establish that the underlying stub method was called. @@ -15909,7 +14141,9 @@ def test_update_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: client.update_product(request=None) # Establish that the underlying stub method was called. @@ -15929,7 +14163,9 @@ def test_delete_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: client.delete_product(request=None) # Establish that the underlying stub method was called. @@ -15950,8 +14186,8 @@ def test_create_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: client.create_reference_image(request=None) # Establish that the underlying stub method was called. @@ -15972,8 +14208,8 @@ def test_delete_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: client.delete_reference_image(request=None) # Establish that the underlying stub method was called. @@ -15994,8 +14230,8 @@ def test_list_reference_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: client.list_reference_images(request=None) # Establish that the underlying stub method was called. @@ -16016,8 +14252,8 @@ def test_get_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: client.get_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16038,8 +14274,8 @@ def test_add_product_to_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: client.add_product_to_product_set(request=None) # Establish that the underlying stub method was called. @@ -16060,8 +14296,8 @@ def test_remove_product_from_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: client.remove_product_from_product_set(request=None) # Establish that the underlying stub method was called. @@ -16082,8 +14318,8 @@ def test_list_products_in_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: client.list_products_in_product_set(request=None) # Establish that the underlying stub method was called. @@ -16104,8 +14340,8 @@ def test_import_product_sets_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: client.import_product_sets(request=None) # Establish that the underlying stub method was called. @@ -16126,13 +14362,12 @@ def test_product_search_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ProductSearchClient( @@ -16143,21 +14378,18 @@ def test_transport_grpc_default(): transports.ProductSearchGrpcTransport, ) - def test_product_search_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProductSearchTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_product_search_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport.__init__') as Transport: Transport.return_value = None transport = transports.ProductSearchTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -16166,24 +14398,24 @@ def test_product_search_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "create_product_set", - "list_product_sets", - "get_product_set", - "update_product_set", - "delete_product_set", - "create_product", - "list_products", - "get_product", - "update_product", - "delete_product", - "create_reference_image", - "delete_reference_image", - "list_reference_images", - "get_reference_image", - "add_product_to_product_set", - "remove_product_from_product_set", - "list_products_in_product_set", - "import_product_sets", + 'create_product_set', + 'list_product_sets', + 'get_product_set', + 'update_product_set', + 'delete_product_set', + 'create_product', + 'list_products', + 'get_product', + 'update_product', + 'delete_product', + 'create_reference_image', + 'delete_reference_image', + 'list_reference_images', + 'get_reference_image', + 'add_product_to_product_set', + 'remove_product_from_product_set', + 'list_products_in_product_set', + 'import_product_sets', ) for method in methods: with pytest.raises(NotImplementedError): @@ -16199,7 +14431,7 @@ def test_product_search_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -16208,33 +14440,26 @@ def test_product_search_base_transport(): def test_product_search_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.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_product_search_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.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport() @@ -16243,15 +14468,15 @@ def test_product_search_base_transport_with_adc(): def test_product_search_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ProductSearchClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -16266,15 +14491,12 @@ def test_product_search_auth_adc(): def test_product_search_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -16288,38 +14510,39 @@ def test_product_search_transport_auth_adc(transport_class): ], ) def test_product_search_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ProductSearchGrpcTransport, grpc_helpers), - (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_product_search_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -16327,9 +14550,9 @@ def test_product_search_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -16340,14 +14563,10 @@ def test_product_search_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -16356,7 +14575,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -16377,77 +14596,61 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_product_search_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.ProductSearchRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ProductSearchRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_product_search_host_no_port(transport_name): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_product_search_host_with_port(transport_name): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_product_search_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -16513,10 +14716,8 @@ def test_product_search_client_transport_session_collision(transport_name): session1 = client1.transport.import_product_sets._session session2 = client2.transport.import_product_sets._session assert session1 != session2 - - def test_product_search_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ProductSearchGrpcTransport( @@ -16529,7 +14730,7 @@ def test_product_search_grpc_transport_channel(): def test_product_search_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ProductSearchGrpcAsyncIOTransport( @@ -16544,20 +14745,12 @@ def test_product_search_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_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: +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_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 @@ -16566,7 +14759,7 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -16596,23 +14789,17 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport # 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.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_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: + 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() @@ -16643,7 +14830,7 @@ def test_product_search_transport_channel_mtls_with_adc(transport_class): def test_product_search_grpc_lro_client(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -16660,7 +14847,7 @@ def test_product_search_grpc_lro_client(): def test_product_search_grpc_lro_async_client(): client = ProductSearchAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -16678,11 +14865,7 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + expected = "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) actual = ProductSearchClient.product_path(project, location, product) assert expected == actual @@ -16699,18 +14882,11 @@ def test_parse_product_path(): actual = ProductSearchClient.parse_product_path(path) assert expected == actual - def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) actual = ProductSearchClient.product_set_path(project, location, product_set) assert expected == actual @@ -16727,21 +14903,13 @@ def test_parse_product_set_path(): actual = ProductSearchClient.parse_product_set_path(path) assert expected == actual - def test_reference_image_path(): project = "squid" location = "clam" product = "whelk" reference_image = "octopus" - expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( - project=project, - location=location, - product=product, - reference_image=reference_image, - ) - actual = ProductSearchClient.reference_image_path( - project, location, product, reference_image - ) + expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format(project=project, location=location, product=product, reference_image=reference_image, ) + actual = ProductSearchClient.reference_image_path(project, location, product, reference_image) assert expected == actual @@ -16758,12 +14926,9 @@ def test_parse_reference_image_path(): actual = ProductSearchClient.parse_reference_image_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ProductSearchClient.common_billing_account_path(billing_account) assert expected == actual @@ -16778,12 +14943,9 @@ def test_parse_common_billing_account_path(): actual = ProductSearchClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ProductSearchClient.common_folder_path(folder) assert expected == actual @@ -16798,12 +14960,9 @@ def test_parse_common_folder_path(): actual = ProductSearchClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ProductSearchClient.common_organization_path(organization) assert expected == actual @@ -16818,12 +14977,9 @@ def test_parse_common_organization_path(): actual = ProductSearchClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ProductSearchClient.common_project_path(project) assert expected == actual @@ -16838,14 +14994,10 @@ def test_parse_common_project_path(): actual = ProductSearchClient.parse_common_project_path(path) assert expected == actual - def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ProductSearchClient.common_location_path(project, location) assert expected == actual @@ -16865,18 +15017,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ProductSearchTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ProductSearchTransport, '_prep_wrapped_messages') as prep: client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ProductSearchTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ProductSearchTransport, '_prep_wrapped_messages') as prep: transport_class = ProductSearchClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -16887,11 +15035,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -16900,11 +15047,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -16912,11 +15058,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -16924,12 +15069,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -16938,14 +15084,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport), - (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -16960,9 +15102,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/__init__.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/__init__.py index cbf94b283c70..191773d5572d 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/__init__.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py index 3cbaccb9bab4..61e00fec874e 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,58 +21,53 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1p4beta1.services.image_annotator import ImageAnnotatorAsyncClient +from google.cloud.vision_v1p4beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p4beta1.services.image_annotator import transports +from google.cloud.vision_v1p4beta1.types import face +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import image_annotator +from google.cloud.vision_v1p4beta1.types import product_search +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.type import latlng_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1p4beta1.services.image_annotator import ( - ImageAnnotatorAsyncClient, - ImageAnnotatorClient, - transports, -) -from google.cloud.vision_v1p4beta1.types import ( - face, - geometry, - image_annotator, - product_search, -) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -88,11 +82,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -100,27 +92,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -131,43 +113,20 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - True, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -181,46 +140,27 @@ def test__read_environment_variables(): ) else: assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ImageAnnotatorClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ImageAnnotatorClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ImageAnnotatorClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ImageAnnotatorClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ImageAnnotatorClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -229,9 +169,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ImageAnnotatorClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -239,9 +177,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -253,9 +189,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -267,9 +201,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -281,9 +213,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -298,167 +228,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ImageAnnotatorClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ImageAnnotatorClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ImageAnnotatorClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ImageAnnotatorClient._get_client_cert_source(None, False) is None - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) - - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ImageAnnotatorClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ImageAnnotatorClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ImageAnnotatorClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageAnnotatorClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ImageAnnotatorClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ImageAnnotatorClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + assert ImageAnnotatorClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageAnnotatorClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ImageAnnotatorClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ImageAnnotatorClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ImageAnnotatorClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ImageAnnotatorClient._get_universe_domain(None, None) - == ImageAnnotatorClient._DEFAULT_UNIVERSE - ) + assert ImageAnnotatorClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageAnnotatorClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageAnnotatorClient._get_universe_domain(None, None) == ImageAnnotatorClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ImageAnnotatorClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -474,8 +320,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -488,20 +333,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -509,68 +348,52 @@ def test_image_annotator_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ImageAnnotatorGrpcTransport, "grpc"), - (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageAnnotatorGrpcTransport, "grpc"), + (transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ImageAnnotatorClient, "grpc"), - (ImageAnnotatorAsyncClient, "grpc_asyncio"), - (ImageAnnotatorClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageAnnotatorClient, "grpc"), + (ImageAnnotatorAsyncClient, "grpc_asyncio"), + (ImageAnnotatorClient, "rest"), +]) def test_image_annotator_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -586,45 +409,30 @@ def test_image_annotator_client_get_transport_class(): assert transport == transports.ImageAnnotatorGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) -def test_image_annotator_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) +def test_image_annotator_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + with mock.patch.object(ImageAnnotatorClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -642,15 +450,13 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -662,7 +468,7 @@ def test_image_annotator_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -682,22 +488,17 @@ def test_image_annotator_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -706,82 +507,48 @@ def test_image_annotator_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "true"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_annotator_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_image_annotator_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -800,22 +567,12 @@ def test_image_annotator_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -836,22 +593,15 @@ def test_image_annotator_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -861,31 +611,19 @@ def test_image_annotator_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageAnnotatorAsyncClient)) def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -893,25 +631,18 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -948,24 +679,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -996,24 +726,23 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1029,28 +758,16 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1060,50 +777,27 @@ def test_image_annotator_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] -) -@mock.patch.object( - ImageAnnotatorClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorClient), -) -@mock.patch.object( - ImageAnnotatorAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ImageAnnotatorAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ImageAnnotatorClient, ImageAnnotatorAsyncClient +]) +@mock.patch.object(ImageAnnotatorClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorClient)) +@mock.patch.object(ImageAnnotatorAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageAnnotatorAsyncClient)) def test_image_annotator_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ImageAnnotatorClient._DEFAULT_UNIVERSE - default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ImageAnnotatorClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1126,19 +820,11 @@ def test_image_annotator_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1146,40 +832,27 @@ def test_image_annotator_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), - ], -) -def test_image_annotator_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest"), +]) +def test_image_annotator_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1188,40 +861,24 @@ def test_image_annotator_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), - ], -) -def test_image_annotator_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageAnnotatorClient, transports.ImageAnnotatorRestTransport, "rest", None), +]) +def test_image_annotator_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1230,14 +887,11 @@ def test_image_annotator_client_client_options_credentials_file( api_audience=None, ) - def test_image_annotator_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ImageAnnotatorClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1252,38 +906,23 @@ def test_image_annotator_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ImageAnnotatorClient, - transports.ImageAnnotatorGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ImageAnnotatorAsyncClient, - transports.ImageAnnotatorGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_image_annotator_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", grpc_helpers), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_annotator_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1311,9 +950,9 @@ def test_image_annotator_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1324,14 +963,11 @@ def test_image_annotator_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) -def test_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) +def test_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1343,10 +979,11 @@ def test_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateImagesResponse() + call.return_value = image_annotator.BatchAnnotateImagesResponse( + ) response = client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1364,26 +1001,25 @@ def test_batch_annotate_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.BatchAnnotateImagesRequest() + request = image_annotator.BatchAnnotateImagesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() - + assert args[0] == image_annotator.BatchAnnotateImagesRequest( + ) def test_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1399,19 +1035,12 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -1424,11 +1053,8 @@ def test_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1442,17 +1068,12 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_images] = mock_rpc request = {} await client.batch_annotate_images(request) @@ -1466,12 +1087,8 @@ async def test_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateImagesRequest, -): +async def test_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1483,12 +1100,11 @@ async def test_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) response = await client.batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1513,18 +1129,14 @@ def test_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1532,11 +1144,7 @@ def test_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val @@ -1550,14 +1158,9 @@ def test_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1566,22 +1169,16 @@ async def test_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) # Establish that the underlying call was made with the expected @@ -1589,14 +1186,9 @@ async def test_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1608,22 +1200,15 @@ async def test_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateFilesRequest, - dict, - ], -) -def test_batch_annotate_files(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateFilesRequest, + dict, +]) +def test_batch_annotate_files(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1635,10 +1220,11 @@ def test_batch_annotate_files(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = image_annotator.BatchAnnotateFilesResponse() + call.return_value = image_annotator.BatchAnnotateFilesResponse( + ) response = client.batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -1656,26 +1242,25 @@ def test_batch_annotate_files_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.BatchAnnotateFilesRequest() + request = image_annotator.BatchAnnotateFilesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.batch_annotate_files), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.batch_annotate_files(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateFilesRequest() - + assert args[0] == image_annotator.BatchAnnotateFilesRequest( + ) def test_batch_annotate_files_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1691,18 +1276,12 @@ def test_batch_annotate_files_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_files in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_files] = mock_rpc request = {} client.batch_annotate_files(request) @@ -1715,11 +1294,8 @@ def test_batch_annotate_files_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_files_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1733,17 +1309,12 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.batch_annotate_files - in client._client._transport._wrapped_methods - ) + assert client._client._transport.batch_annotate_files in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_annotate_files - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.batch_annotate_files] = mock_rpc request = {} await client.batch_annotate_files(request) @@ -1757,12 +1328,8 @@ async def test_batch_annotate_files_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_batch_annotate_files_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.BatchAnnotateFilesRequest, -): +async def test_batch_annotate_files_async(transport: str = 'grpc_asyncio', request_type=image_annotator.BatchAnnotateFilesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1774,12 +1341,11 @@ async def test_batch_annotate_files_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateFilesResponse() - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateFilesResponse( + )) response = await client.batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -1804,20 +1370,14 @@ def test_batch_annotate_files_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateFilesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_annotate_files( - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1825,13 +1385,7 @@ def test_batch_annotate_files_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val @@ -1845,16 +1399,9 @@ def test_batch_annotate_files_flattened_error(): with pytest.raises(ValueError): client.batch_annotate_files( image_annotator.BatchAnnotateFilesRequest(), - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) - @pytest.mark.asyncio async def test_batch_annotate_files_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -1863,24 +1410,16 @@ async def test_batch_annotate_files_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = image_annotator.BatchAnnotateFilesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateFilesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateFilesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.batch_annotate_files( - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -1888,16 +1427,9 @@ async def test_batch_annotate_files_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val - @pytest.mark.asyncio async def test_batch_annotate_files_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -1909,24 +1441,15 @@ async def test_batch_annotate_files_flattened_error_async(): with pytest.raises(ValueError): await client.batch_annotate_files( image_annotator.BatchAnnotateFilesRequest(), - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateImagesRequest, - dict, - ], -) -def test_async_batch_annotate_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateImagesRequest, + dict, +]) +def test_async_batch_annotate_images(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1938,10 +1461,10 @@ def test_async_batch_annotate_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.async_batch_annotate_images(request) # Establish that the underlying gRPC stub method was called. @@ -1959,26 +1482,25 @@ def test_async_batch_annotate_images_non_empty_request_with_auto_populated_field # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.AsyncBatchAnnotateImagesRequest() + request = image_annotator.AsyncBatchAnnotateImagesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.async_batch_annotate_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.async_batch_annotate_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest() - + assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest( + ) def test_async_batch_annotate_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1994,19 +1516,12 @@ def test_async_batch_annotate_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_images] = mock_rpc request = {} client.async_batch_annotate_images(request) @@ -2024,11 +1539,8 @@ def test_async_batch_annotate_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2042,17 +1554,12 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.async_batch_annotate_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.async_batch_annotate_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.async_batch_annotate_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.async_batch_annotate_images] = mock_rpc request = {} await client.async_batch_annotate_images(request) @@ -2071,12 +1578,8 @@ async def test_async_batch_annotate_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_images_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.AsyncBatchAnnotateImagesRequest, -): +async def test_async_batch_annotate_images_async(transport: str = 'grpc_asyncio', request_type=image_annotator.AsyncBatchAnnotateImagesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2088,11 +1591,11 @@ async def test_async_batch_annotate_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.async_batch_annotate_images(request) @@ -2118,21 +1621,15 @@ def test_async_batch_annotate_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.async_batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) # Establish that the underlying call was made with the expected @@ -2140,16 +1637,10 @@ def test_async_batch_annotate_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val arg = args[0].output_config - mock_val = image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ) + mock_val = image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')) assert arg == mock_val @@ -2163,17 +1654,10 @@ def test_async_batch_annotate_images_flattened_error(): with pytest.raises(ValueError): client.async_batch_annotate_images( image_annotator.AsyncBatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) - @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -2182,25 +1666,19 @@ async def test_async_batch_annotate_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.async_batch_annotate_images( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) # Establish that the underlying call was made with the expected @@ -2208,19 +1686,12 @@ async def test_async_batch_annotate_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ] + mock_val = [image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))] assert arg == mock_val arg = args[0].output_config - mock_val = image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ) + mock_val = image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')) assert arg == mock_val - @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -2232,25 +1703,16 @@ async def test_async_batch_annotate_images_flattened_error_async(): with pytest.raises(ValueError): await client.async_batch_annotate_images( image_annotator.AsyncBatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) -def test_async_batch_annotate_files(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) +def test_async_batch_annotate_files(request_type, transport: str = 'grpc'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2262,10 +1724,10 @@ def test_async_batch_annotate_files(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.async_batch_annotate_files(request) # Establish that the underlying gRPC stub method was called. @@ -2283,26 +1745,25 @@ def test_async_batch_annotate_files_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = image_annotator.AsyncBatchAnnotateFilesRequest() + request = image_annotator.AsyncBatchAnnotateFilesRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.async_batch_annotate_files(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() - + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest( + ) def test_async_batch_annotate_files_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2318,19 +1779,12 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -2348,11 +1802,8 @@ def test_async_batch_annotate_files_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2366,17 +1817,12 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.async_batch_annotate_files - in client._client._transport._wrapped_methods - ) + assert client._client._transport.async_batch_annotate_files in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.async_batch_annotate_files - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.async_batch_annotate_files] = mock_rpc request = {} await client.async_batch_annotate_files(request) @@ -2395,12 +1841,8 @@ async def test_async_batch_annotate_files_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_async_batch_annotate_files_async( - transport: str = "grpc_asyncio", - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +async def test_async_batch_annotate_files_async(transport: str = 'grpc_asyncio', request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2412,11 +1854,11 @@ async def test_async_batch_annotate_files_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.async_batch_annotate_files(request) @@ -2442,34 +1884,22 @@ def test_async_batch_annotate_files_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + _, args, _ = call.mock_calls[0] + arg = args[0].requests + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val @@ -2483,16 +1913,9 @@ def test_async_batch_annotate_files_flattened_error(): with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): client = ImageAnnotatorAsyncClient( @@ -2501,24 +1924,18 @@ async def test_async_batch_annotate_files_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.async_batch_annotate_files( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) # Establish that the underlying call was made with the expected @@ -2526,16 +1943,9 @@ async def test_async_batch_annotate_files_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].requests - mock_val = [ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ] + mock_val = [image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))] assert arg == mock_val - @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): client = ImageAnnotatorAsyncClient( @@ -2547,13 +1957,7 @@ async def test_async_batch_annotate_files_flattened_error_async(): with pytest.raises(ValueError): await client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -2571,19 +1975,12 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_images] = mock_rpc request = {} client.batch_annotate_images(request) @@ -2598,57 +1995,52 @@ def test_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_images_rest_required_fields( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_required_fields(request_type=image_annotator.BatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2658,24 +2050,24 @@ def test_batch_annotate_images_rest_required_fields( return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_images_rest_flattened(): @@ -2685,7 +2077,7 @@ def test_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateImagesResponse() @@ -2694,11 +2086,7 @@ def test_batch_annotate_images_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) mock_args.update(sample_request) @@ -2708,7 +2096,7 @@ def test_batch_annotate_images_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2718,12 +2106,10 @@ def test_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/images:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p4beta1/images:annotate" % client.transport._host, args[1]) -def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2734,11 +2120,7 @@ def test_batch_annotate_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_images( image_annotator.BatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], ) @@ -2756,18 +2138,12 @@ def test_batch_annotate_files_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_annotate_files in client._transport._wrapped_methods - ) + assert client._transport.batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_annotate_files] = mock_rpc request = {} client.batch_annotate_files(request) @@ -2782,57 +2158,52 @@ def test_batch_annotate_files_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_batch_annotate_files_rest_required_fields( - request_type=image_annotator.BatchAnnotateFilesRequest, -): +def test_batch_annotate_files_rest_required_fields(request_type=image_annotator.BatchAnnotateFilesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateFilesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2842,24 +2213,24 @@ def test_batch_annotate_files_rest_required_fields( return_value = image_annotator.BatchAnnotateFilesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_files(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_batch_annotate_files_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.batch_annotate_files._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_batch_annotate_files_rest_flattened(): @@ -2869,7 +2240,7 @@ def test_batch_annotate_files_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = image_annotator.BatchAnnotateFilesResponse() @@ -2878,13 +2249,7 @@ def test_batch_annotate_files_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) mock_args.update(sample_request) @@ -2894,7 +2259,7 @@ def test_batch_annotate_files_rest_flattened(): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateFilesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2904,12 +2269,10 @@ def test_batch_annotate_files_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/files:annotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p4beta1/files:annotate" % client.transport._host, args[1]) -def test_batch_annotate_files_rest_flattened_error(transport: str = "rest"): +def test_batch_annotate_files_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2920,13 +2283,7 @@ def test_batch_annotate_files_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.batch_annotate_files( image_annotator.BatchAnnotateFilesRequest(), - requests=[ - image_annotator.AnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -2944,19 +2301,12 @@ def test_async_batch_annotate_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_images - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_images] = mock_rpc request = {} client.async_batch_annotate_images(request) @@ -2975,89 +2325,76 @@ def test_async_batch_annotate_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_async_batch_annotate_images_rest_required_fields( - request_type=image_annotator.AsyncBatchAnnotateImagesRequest, -): +def test_async_batch_annotate_images_rest_required_fields(request_type=image_annotator.AsyncBatchAnnotateImagesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_images._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_async_batch_annotate_images_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.async_batch_annotate_images._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "requests", - "outputConfig", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("requests", "outputConfig", ))) def test_async_batch_annotate_images_rest_flattened(): @@ -3067,23 +2404,17 @@ def test_async_batch_annotate_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method sample_request = {} # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) mock_args.update(sample_request) @@ -3091,7 +2422,7 @@ def test_async_batch_annotate_images_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3101,12 +2432,10 @@ def test_async_batch_annotate_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/images:asyncBatchAnnotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p4beta1/images:asyncBatchAnnotate" % client.transport._host, args[1]) -def test_async_batch_annotate_images_rest_flattened_error(transport: str = "rest"): +def test_async_batch_annotate_images_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3117,14 +2446,8 @@ def test_async_batch_annotate_images_rest_flattened_error(transport: str = "rest with pytest.raises(ValueError): client.async_batch_annotate_images( image_annotator.AsyncBatchAnnotateImagesRequest(), - requests=[ - image_annotator.AnnotateImageRequest( - image=image_annotator.Image(content=b"content_blob") - ) - ], - output_config=image_annotator.OutputConfig( - gcs_destination=image_annotator.GcsDestination(uri="uri_value") - ), + requests=[image_annotator.AnnotateImageRequest(image=image_annotator.Image(content=b'content_blob'))], + output_config=image_annotator.OutputConfig(gcs_destination=image_annotator.GcsDestination(uri='uri_value')), ) @@ -3142,19 +2465,12 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.async_batch_annotate_files - in client._transport._wrapped_methods - ) + assert client._transport.async_batch_annotate_files in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.async_batch_annotate_files - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.async_batch_annotate_files] = mock_rpc request = {} client.async_batch_annotate_files(request) @@ -3173,81 +2489,76 @@ def test_async_batch_annotate_files_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_async_batch_annotate_files_rest_required_fields( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_required_fields(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): transport_class = transports.ImageAnnotatorRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).async_batch_annotate_files._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).async_batch_annotate_files._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_async_batch_annotate_files_rest_unset_required_fields(): - transport = transports.ImageAnnotatorRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ImageAnnotatorRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.async_batch_annotate_files._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("requests",))) + assert set(unset_fields) == (set(()) & set(("requests", ))) def test_async_batch_annotate_files_rest_flattened(): @@ -3257,22 +2568,16 @@ def test_async_batch_annotate_files_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method sample_request = {} # get truthy value for each flattened field mock_args = dict( - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) mock_args.update(sample_request) @@ -3280,7 +2585,7 @@ def test_async_batch_annotate_files_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3290,12 +2595,10 @@ def test_async_batch_annotate_files_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/files:asyncBatchAnnotate" % client.transport._host, args[1] - ) + assert path_template.validate("%s/v1p4beta1/files:asyncBatchAnnotate" % client.transport._host, args[1]) -def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest"): +def test_async_batch_annotate_files_rest_flattened_error(transport: str = 'rest'): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3306,13 +2609,7 @@ def test_async_batch_annotate_files_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.async_batch_annotate_files( image_annotator.AsyncBatchAnnotateFilesRequest(), - requests=[ - image_annotator.AsyncAnnotateFileRequest( - input_config=image_annotator.InputConfig( - gcs_source=image_annotator.GcsSource(uri="uri_value") - ) - ) - ], + requests=[image_annotator.AsyncAnnotateFileRequest(input_config=image_annotator.InputConfig(gcs_source=image_annotator.GcsSource(uri='uri_value')))], ) @@ -3354,7 +2651,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ImageAnnotatorClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -3376,7 +2674,6 @@ def test_transport_instance(): client = ImageAnnotatorClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( @@ -3391,23 +2688,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - transports.ImageAnnotatorRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + transports.ImageAnnotatorRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ImageAnnotatorClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3417,7 +2709,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -3432,8 +2725,8 @@ def test_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateImagesResponse() client.batch_annotate_images(request=None) @@ -3455,8 +2748,8 @@ def test_batch_annotate_files_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: call.return_value = image_annotator.BatchAnnotateFilesResponse() client.batch_annotate_files(request=None) @@ -3478,9 +2771,9 @@ def test_async_batch_annotate_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.async_batch_annotate_images), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.async_batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -3501,9 +2794,9 @@ def test_async_batch_annotate_files_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.async_batch_annotate_files), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -3523,7 +2816,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -3539,12 +2833,11 @@ async def test_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateImagesResponse( + )) await client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -3566,12 +2859,11 @@ async def test_batch_annotate_files_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - image_annotator.BatchAnnotateFilesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_annotator.BatchAnnotateFilesResponse( + )) await client.batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -3593,11 +2885,11 @@ async def test_async_batch_annotate_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.async_batch_annotate_images(request=None) @@ -3620,11 +2912,11 @@ async def test_async_batch_annotate_files_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.async_batch_annotate_files(request=None) @@ -3643,23 +2935,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_batch_annotate_images_rest_bad_request( - request_type=image_annotator.BatchAnnotateImagesRequest, -): +def test_batch_annotate_images_rest_bad_request(request_type=image_annotator.BatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3668,16 +2957,14 @@ def test_batch_annotate_images_rest_bad_request( client.batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateImagesRequest, + dict, +]) def test_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -3685,9 +2972,10 @@ def test_batch_annotate_images_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateImagesResponse() + return_value = image_annotator.BatchAnnotateImagesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -3696,7 +2984,7 @@ def test_batch_annotate_images_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_images(request) @@ -3709,30 +2997,19 @@ def test_batch_annotate_images_rest_call_success(request_type): def test_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateImagesRequest.pb( - image_annotator.BatchAnnotateImagesRequest() - ) + pb_message = image_annotator.BatchAnnotateImagesRequest.pb(image_annotator.BatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3743,53 +3020,39 @@ def test_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateImagesResponse.to_json( - image_annotator.BatchAnnotateImagesResponse() - ) + return_value = image_annotator.BatchAnnotateImagesResponse.to_json(image_annotator.BatchAnnotateImagesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateImagesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateImagesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateImagesResponse(), metadata - client.batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_batch_annotate_files_rest_bad_request( - request_type=image_annotator.BatchAnnotateFilesRequest, -): +def test_batch_annotate_files_rest_bad_request(request_type=image_annotator.BatchAnnotateFilesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3798,16 +3061,14 @@ def test_batch_annotate_files_rest_bad_request( client.batch_annotate_files(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.BatchAnnotateFilesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.BatchAnnotateFilesRequest, + dict, +]) def test_batch_annotate_files_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -3815,9 +3076,10 @@ def test_batch_annotate_files_rest_call_success(request_type): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. - return_value = image_annotator.BatchAnnotateFilesResponse() + return_value = image_annotator.BatchAnnotateFilesResponse( + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -3826,7 +3088,7 @@ def test_batch_annotate_files_rest_call_success(request_type): # Convert return value to protobuf type return_value = image_annotator.BatchAnnotateFilesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.batch_annotate_files(request) @@ -3839,30 +3101,19 @@ def test_batch_annotate_files_rest_call_success(request_type): def test_batch_annotate_files_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_batch_annotate_files" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_batch_annotate_files_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_files" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_files") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_batch_annotate_files_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_batch_annotate_files") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.BatchAnnotateFilesRequest.pb( - image_annotator.BatchAnnotateFilesRequest() - ) + pb_message = image_annotator.BatchAnnotateFilesRequest.pb(image_annotator.BatchAnnotateFilesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3873,53 +3124,39 @@ def test_batch_annotate_files_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = image_annotator.BatchAnnotateFilesResponse.to_json( - image_annotator.BatchAnnotateFilesResponse() - ) + return_value = image_annotator.BatchAnnotateFilesResponse.to_json(image_annotator.BatchAnnotateFilesResponse()) req.return_value.content = return_value request = image_annotator.BatchAnnotateFilesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = image_annotator.BatchAnnotateFilesResponse() - post_with_metadata.return_value = ( - image_annotator.BatchAnnotateFilesResponse(), - metadata, - ) + post_with_metadata.return_value = image_annotator.BatchAnnotateFilesResponse(), metadata - client.batch_annotate_files( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.batch_annotate_files(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_async_batch_annotate_images_rest_bad_request( - request_type=image_annotator.AsyncBatchAnnotateImagesRequest, -): +def test_async_batch_annotate_images_rest_bad_request(request_type=image_annotator.AsyncBatchAnnotateImagesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3928,16 +3165,14 @@ def test_async_batch_annotate_images_rest_bad_request( client.async_batch_annotate_images(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateImagesRequest, + dict, +]) def test_async_batch_annotate_images_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -3945,15 +3180,15 @@ def test_async_batch_annotate_images_rest_call_success(request_type): 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_images(request) @@ -3966,32 +3201,20 @@ def test_async_batch_annotate_images_rest_call_success(request_type): def test_async_batch_annotate_images_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_images" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_async_batch_annotate_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_images" - ) as pre: + 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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_images") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.AsyncBatchAnnotateImagesRequest.pb( - image_annotator.AsyncBatchAnnotateImagesRequest() - ) + pb_message = image_annotator.AsyncBatchAnnotateImagesRequest.pb(image_annotator.AsyncBatchAnnotateImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4006,7 +3229,7 @@ def test_async_batch_annotate_images_rest_interceptors(null_interceptor): req.return_value.content = return_value request = image_annotator.AsyncBatchAnnotateImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4014,36 +3237,27 @@ def test_async_batch_annotate_images_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.async_batch_annotate_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.async_batch_annotate_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_async_batch_annotate_files_rest_bad_request( - request_type=image_annotator.AsyncBatchAnnotateFilesRequest, -): +def test_async_batch_annotate_files_rest_bad_request(request_type=image_annotator.AsyncBatchAnnotateFilesRequest): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding request_init = {} 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4052,16 +3266,14 @@ def test_async_batch_annotate_files_rest_bad_request( client.async_batch_annotate_files(request) -@pytest.mark.parametrize( - "request_type", - [ - image_annotator.AsyncBatchAnnotateFilesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + image_annotator.AsyncBatchAnnotateFilesRequest, + dict, +]) def test_async_batch_annotate_files_rest_call_success(request_type): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding @@ -4069,15 +3281,15 @@ def test_async_batch_annotate_files_rest_call_success(request_type): 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.async_batch_annotate_files(request) @@ -4090,32 +3302,20 @@ def test_async_batch_annotate_files_rest_call_success(request_type): def test_async_batch_annotate_files_rest_interceptors(null_interceptor): transport = transports.ImageAnnotatorRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ImageAnnotatorRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ImageAnnotatorRestInterceptor(), + ) client = ImageAnnotatorClient(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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files" - ) as post, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, - "post_async_batch_annotate_files_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files" - ) as pre: + 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.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files") as post, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "post_async_batch_annotate_files_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageAnnotatorRestInterceptor, "pre_async_batch_annotate_files") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb( - image_annotator.AsyncBatchAnnotateFilesRequest() - ) + pb_message = image_annotator.AsyncBatchAnnotateFilesRequest.pb(image_annotator.AsyncBatchAnnotateFilesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4130,7 +3330,7 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): req.return_value.content = return_value request = image_annotator.AsyncBatchAnnotateFilesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4138,22 +3338,16 @@ def test_async_batch_annotate_files_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.async_batch_annotate_files( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.async_batch_annotate_files(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -4168,8 +3362,8 @@ def test_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_images), "__call__" - ) as call: + type(client.transport.batch_annotate_images), + '__call__') as call: client.batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -4190,8 +3384,8 @@ def test_batch_annotate_files_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.batch_annotate_files), "__call__" - ) as call: + type(client.transport.batch_annotate_files), + '__call__') as call: client.batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -4212,8 +3406,8 @@ def test_async_batch_annotate_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_images), "__call__" - ) as call: + type(client.transport.async_batch_annotate_images), + '__call__') as call: client.async_batch_annotate_images(request=None) # Establish that the underlying stub method was called. @@ -4234,8 +3428,8 @@ def test_async_batch_annotate_files_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.async_batch_annotate_files), "__call__" - ) as call: + type(client.transport.async_batch_annotate_files), + '__call__') as call: client.async_batch_annotate_files(request=None) # Establish that the underlying stub method was called. @@ -4256,13 +3450,12 @@ def test_image_annotator_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ImageAnnotatorClient( @@ -4273,21 +3466,18 @@ def test_transport_grpc_default(): transports.ImageAnnotatorGrpcTransport, ) - def test_image_annotator_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_image_annotator_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__') as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4296,10 +3486,10 @@ def test_image_annotator_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "batch_annotate_images", - "batch_annotate_files", - "async_batch_annotate_images", - "async_batch_annotate_files", + 'batch_annotate_images', + 'batch_annotate_files', + 'async_batch_annotate_images', + 'async_batch_annotate_files', ) for method in methods: with pytest.raises(NotImplementedError): @@ -4315,7 +3505,7 @@ def test_image_annotator_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4324,33 +3514,26 @@ def test_image_annotator_base_transport(): def test_image_annotator_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.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_image_annotator_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.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() @@ -4359,15 +3542,15 @@ def test_image_annotator_base_transport_with_adc(): def test_image_annotator_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -4382,15 +3565,12 @@ def test_image_annotator_auth_adc(): def test_image_annotator_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -4404,38 +3584,39 @@ def test_image_annotator_transport_auth_adc(transport_class): ], ) def test_image_annotator_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ImageAnnotatorGrpcTransport, grpc_helpers), - (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_image_annotator_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -4443,9 +3624,9 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -4456,14 +3637,10 @@ def test_image_annotator_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4472,7 +3649,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -4493,77 +3670,61 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_image_annotator_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.ImageAnnotatorRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ImageAnnotatorRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_no_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_image_annotator_host_with_port(transport_name): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_image_annotator_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4587,10 +3748,8 @@ def test_image_annotator_client_transport_session_collision(transport_name): session1 = client1.transport.async_batch_annotate_files._session session2 = client2.transport.async_batch_annotate_files._session assert session1 != session2 - - def test_image_annotator_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcTransport( @@ -4603,7 +3762,7 @@ def test_image_annotator_grpc_transport_channel(): def test_image_annotator_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ImageAnnotatorGrpcAsyncIOTransport( @@ -4618,22 +3777,12 @@ def test_image_annotator_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) def test_image_annotator_transport_channel_mtls_with_client_cert_source( - transport_class, + 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: + 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 @@ -4642,7 +3791,7 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -4672,23 +3821,17 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( # 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.ImageAnnotatorGrpcTransport, - transports.ImageAnnotatorGrpcAsyncIOTransport, - ], -) -def test_image_annotator_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ImageAnnotatorGrpcTransport, transports.ImageAnnotatorGrpcAsyncIOTransport]) +def test_image_annotator_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: + 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() @@ -4719,7 +3862,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -4736,7 +3879,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -4754,11 +3897,7 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + expected = "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) actual = ImageAnnotatorClient.product_path(project, location, product) assert expected == actual @@ -4775,18 +3914,11 @@ def test_parse_product_path(): actual = ImageAnnotatorClient.parse_product_path(path) assert expected == actual - def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) actual = ImageAnnotatorClient.product_set_path(project, location, product_set) assert expected == actual @@ -4803,12 +3935,9 @@ def test_parse_product_set_path(): actual = ImageAnnotatorClient.parse_product_set_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ImageAnnotatorClient.common_billing_account_path(billing_account) assert expected == actual @@ -4823,12 +3952,9 @@ def test_parse_common_billing_account_path(): actual = ImageAnnotatorClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -4843,12 +3969,9 @@ def test_parse_common_folder_path(): actual = ImageAnnotatorClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -4863,12 +3986,9 @@ def test_parse_common_organization_path(): actual = ImageAnnotatorClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -4883,14 +4003,10 @@ def test_parse_common_project_path(): actual = ImageAnnotatorClient.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, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ImageAnnotatorClient.common_location_path(project, location) assert expected == actual @@ -4910,18 +4026,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: client = ImageAnnotatorClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ImageAnnotatorTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ImageAnnotatorTransport, '_prep_wrapped_messages') as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -4932,11 +4044,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -4945,11 +4056,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ImageAnnotatorAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -4957,11 +4067,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -4969,12 +4078,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ImageAnnotatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -4983,14 +4093,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), - (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport), + (ImageAnnotatorAsyncClient, transports.ImageAnnotatorGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5005,9 +4111,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_product_search.py b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_product_search.py index 16924d11f086..7ed8bec55a57 100644 --- a/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_product_search.py +++ b/packages/google-cloud-vision/tests/unit/gapic/vision_v1p4beta1/test_product_search.py @@ -14,7 +14,6 @@ # limitations under the License. # import os - # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -22,58 +21,56 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import AsyncIterable, Iterable +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format import json import math - +import pytest from google.api_core import api_core_version -from google.protobuf import json_format -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest -from requests import PreparedRequest, Request, Response +from 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 try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import ( - future, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - operation, - operations_v1, - path_template, -) from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template from google.api_core import retry as retries -import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.vision_v1p4beta1.services.product_search import ProductSearchAsyncClient +from google.cloud.vision_v1p4beta1.services.product_search import ProductSearchClient +from google.cloud.vision_v1p4beta1.services.product_search import pagers +from google.cloud.vision_v1p4beta1.services.product_search import transports +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore +import google.auth + -from google.cloud.vision_v1p4beta1.services.product_search import ( - ProductSearchAsyncClient, - ProductSearchClient, - pagers, - transports, -) -from google.cloud.vision_v1p4beta1.types import geometry, product_search_service CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -88,11 +85,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -100,27 +95,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -131,26 +116,11 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ProductSearchClient._get_default_mtls_endpoint(None) is None - assert ( - ProductSearchClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - + assert ProductSearchClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi def test__read_environment_variables(): assert ProductSearchClient._read_environment_variables() == (False, "auto", None) @@ -159,11 +129,7 @@ def test__read_environment_variables(): assert ProductSearchClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -177,46 +143,27 @@ def test__read_environment_variables(): ) else: assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ProductSearchClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ProductSearchClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ProductSearchClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ProductSearchClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert ProductSearchClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -225,9 +172,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert ProductSearchClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -235,9 +180,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert ProductSearchClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -249,9 +192,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -263,9 +204,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -277,9 +216,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -294,167 +231,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): ProductSearchClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert ProductSearchClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert ProductSearchClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert ProductSearchClient._get_client_cert_source(None, False) is None - assert ( - ProductSearchClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - ProductSearchClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - ProductSearchClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - ProductSearchClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert ProductSearchClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProductSearchClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ProductSearchClient._DEFAULT_UNIVERSE - default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - ProductSearchClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "always") - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == ProductSearchClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - ProductSearchClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert ProductSearchClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "always") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProductSearchClient.DEFAULT_MTLS_ENDPOINT + assert ProductSearchClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProductSearchClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - ProductSearchClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + ProductSearchClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - ProductSearchClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - ProductSearchClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - ProductSearchClient._get_universe_domain(None, None) - == ProductSearchClient._DEFAULT_UNIVERSE - ) + assert ProductSearchClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProductSearchClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProductSearchClient._get_universe_domain(None, None) == ProductSearchClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: ProductSearchClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -470,8 +323,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -484,20 +336,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ProductSearchClient, "grpc"), - (ProductSearchAsyncClient, "grpc_asyncio"), - (ProductSearchClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductSearchClient, "grpc"), + (ProductSearchAsyncClient, "grpc_asyncio"), + (ProductSearchClient, "rest"), +]) def test_product_search_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -505,68 +351,52 @@ def test_product_search_client_from_service_account_info(client_class, transport assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.ProductSearchGrpcTransport, "grpc"), - (transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProductSearchRestTransport, "rest"), - ], -) -def test_product_search_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProductSearchGrpcTransport, "grpc"), + (transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProductSearchRestTransport, "rest"), +]) +def test_product_search_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (ProductSearchClient, "grpc"), - (ProductSearchAsyncClient, "grpc_asyncio"), - (ProductSearchClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (ProductSearchClient, "grpc"), + (ProductSearchAsyncClient, "grpc_asyncio"), + (ProductSearchClient, "rest"), +]) def test_product_search_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://vision.googleapis.com' ) @@ -582,45 +412,30 @@ def test_product_search_client_get_transport_class(): assert transport == transports.ProductSearchGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), - ], -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) -def test_product_search_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) +def test_product_search_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(ProductSearchClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + with mock.patch.object(ProductSearchClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -638,15 +453,13 @@ def test_product_search_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -658,7 +471,7 @@ def test_product_search_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -678,22 +491,17 @@ def test_product_search_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -702,82 +510,48 @@ def test_product_search_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "true"), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "true"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", "false"), +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_product_search_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_product_search_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -796,22 +570,12 @@ def test_product_search_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -832,22 +596,15 @@ def test_product_search_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -857,31 +614,19 @@ def test_product_search_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [ProductSearchClient, ProductSearchAsyncClient] -) -@mock.patch.object( - ProductSearchClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(ProductSearchAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ProductSearchClient, ProductSearchAsyncClient +]) +@mock.patch.object(ProductSearchClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProductSearchAsyncClient)) def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -889,25 +634,18 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -944,24 +682,23 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -992,24 +729,23 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1025,28 +761,16 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - ( - api_endpoint, - cert_source, - ) = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1056,50 +780,27 @@ def test_product_search_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [ProductSearchClient, ProductSearchAsyncClient] -) -@mock.patch.object( - ProductSearchClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchClient), -) -@mock.patch.object( - ProductSearchAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(ProductSearchAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + ProductSearchClient, ProductSearchAsyncClient +]) +@mock.patch.object(ProductSearchClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchClient)) +@mock.patch.object(ProductSearchAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProductSearchAsyncClient)) def test_product_search_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ProductSearchClient._DEFAULT_UNIVERSE - default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = ProductSearchClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1122,19 +823,11 @@ def test_product_search_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1142,40 +835,27 @@ def test_product_search_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), - ], -) -def test_product_search_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio"), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest"), +]) +def test_product_search_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1184,40 +864,24 @@ def test_product_search_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ProductSearchClient, - transports.ProductSearchGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (ProductSearchClient, transports.ProductSearchRestTransport, "rest", None), - ], -) -def test_product_search_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", grpc_helpers), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProductSearchClient, transports.ProductSearchRestTransport, "rest", None), +]) +def test_product_search_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1226,14 +890,11 @@ def test_product_search_client_client_options_credentials_file( api_audience=None, ) - def test_product_search_client_client_options_from_dict(): - with mock.patch( - "google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = ProductSearchClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1248,38 +909,23 @@ def test_product_search_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - ProductSearchClient, - transports.ProductSearchGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - ProductSearchAsyncClient, - transports.ProductSearchGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_product_search_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", grpc_helpers), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_product_search_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1307,9 +953,9 @@ def test_product_search_client_create_channel_credentials_file( credentials_file=None, quota_project_id=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=None, default_host="vision.googleapis.com", ssl_credentials=None, @@ -1320,14 +966,11 @@ def test_product_search_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductSetRequest, - dict, - ], -) -def test_create_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductSetRequest, + dict, +]) +def test_create_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1339,12 +982,12 @@ def test_create_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.create_product_set(request) @@ -1356,8 +999,8 @@ def test_create_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_create_product_set_non_empty_request_with_auto_populated_field(): @@ -1365,33 +1008,30 @@ def test_create_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateProductSetRequest( - parent="parent_value", - product_set_id="product_set_id_value", + parent='parent_value', + product_set_id='product_set_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.create_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateProductSetRequest( - parent="parent_value", - product_set_id="product_set_id_value", + parent='parent_value', + product_set_id='product_set_id_value', ) - def test_create_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1406,18 +1046,12 @@ def test_create_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_product_set in client._transport._wrapped_methods - ) + assert client._transport.create_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_product_set] = mock_rpc request = {} client.create_product_set(request) @@ -1430,11 +1064,8 @@ def test_create_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1448,17 +1079,12 @@ async def test_create_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_product_set] = mock_rpc request = {} await client.create_product_set(request) @@ -1472,12 +1098,8 @@ async def test_create_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateProductSetRequest, -): +async def test_create_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1489,15 +1111,13 @@ async def test_create_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.create_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -1508,15 +1128,14 @@ async def test_create_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_create_product_set_async_from_dict(): await test_create_product_set_async(request_type=dict) - def test_create_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1526,12 +1145,12 @@ def test_create_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductSetRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.create_product_set(request) @@ -1543,9 +1162,9 @@ def test_create_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1558,15 +1177,13 @@ async def test_create_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductSetRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + type(client.transport.create_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.create_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -1577,9 +1194,9 @@ async def test_create_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_product_set_flattened(): @@ -1589,16 +1206,16 @@ def test_create_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_product_set( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) # Establish that the underlying call was made with the expected @@ -1606,13 +1223,13 @@ def test_create_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].product_set_id - mock_val = "product_set_id_value" + mock_val = 'product_set_id_value' assert arg == mock_val @@ -1626,12 +1243,11 @@ def test_create_product_set_flattened_error(): with pytest.raises(ValueError): client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) - @pytest.mark.asyncio async def test_create_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -1640,20 +1256,18 @@ async def test_create_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_product_set( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) # Establish that the underlying call was made with the expected @@ -1661,16 +1275,15 @@ async def test_create_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].product_set_id - mock_val = "product_set_id_value" + mock_val = 'product_set_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -1682,20 +1295,17 @@ async def test_create_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductSetsRequest, - dict, - ], -) -def test_list_product_sets(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductSetsRequest, + dict, +]) +def test_list_product_sets(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1707,11 +1317,11 @@ def test_list_product_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_product_sets(request) @@ -1723,7 +1333,7 @@ def test_list_product_sets(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_product_sets_non_empty_request_with_auto_populated_field(): @@ -1731,33 +1341,30 @@ def test_list_product_sets_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductSetsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_product_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_product_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductSetsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_product_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1776,12 +1383,8 @@ def test_list_product_sets_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_product_sets] = mock_rpc request = {} client.list_product_sets(request) @@ -1794,11 +1397,8 @@ def test_list_product_sets_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_product_sets_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_product_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1812,17 +1412,12 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_product_sets - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_product_sets in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_product_sets - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_product_sets] = mock_rpc request = {} await client.list_product_sets(request) @@ -1836,12 +1431,8 @@ async def test_list_product_sets_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_product_sets_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductSetsRequest, -): +async def test_list_product_sets_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductSetsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1853,14 +1444,12 @@ async def test_list_product_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse( + next_page_token='next_page_token_value', + )) response = await client.list_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -1871,14 +1460,13 @@ async def test_list_product_sets_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_product_sets_async_from_dict(): await test_list_product_sets_async(request_type=dict) - def test_list_product_sets_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1888,12 +1476,12 @@ def test_list_product_sets_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: call.return_value = product_search_service.ListProductSetsResponse() client.list_product_sets(request) @@ -1905,9 +1493,9 @@ def test_list_product_sets_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1920,15 +1508,13 @@ async def test_list_product_sets_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse() - ) + type(client.transport.list_product_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse()) await client.list_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -1939,9 +1525,9 @@ async def test_list_product_sets_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_product_sets_flattened(): @@ -1951,14 +1537,14 @@ def test_list_product_sets_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_product_sets( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -1966,7 +1552,7 @@ def test_list_product_sets_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -1980,10 +1566,9 @@ def test_list_product_sets_flattened_error(): with pytest.raises(ValueError): client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_product_sets_flattened_async(): client = ProductSearchAsyncClient( @@ -1992,18 +1577,16 @@ async def test_list_product_sets_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductSetsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_product_sets( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -2011,10 +1594,9 @@ async def test_list_product_sets_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_product_sets_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2026,7 +1608,7 @@ async def test_list_product_sets_flattened_error_async(): with pytest.raises(ValueError): await client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -2038,8 +1620,8 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2048,17 +1630,17 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2073,7 +1655,9 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_product_sets(request={}, retry=retry, timeout=timeout) @@ -2083,9 +1667,8 @@ def test_list_product_sets_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in results) - - + assert all(isinstance(i, product_search_service.ProductSet) + for i in results) def test_list_product_sets_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2094,8 +1677,8 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2104,17 +1687,17 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2125,10 +1708,9 @@ def test_list_product_sets_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_product_sets(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_product_sets_async_pager(): client = ProductSearchAsyncClient( @@ -2137,10 +1719,8 @@ async def test_list_product_sets_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_product_sets), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2149,17 +1729,17 @@ async def test_list_product_sets_async_pager(): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2169,16 +1749,15 @@ async def test_list_product_sets_async_pager(): ), RuntimeError, ) - async_pager = await client.list_product_sets( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_product_sets(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in responses) + assert all(isinstance(i, product_search_service.ProductSet) + for i in responses) @pytest.mark.asyncio @@ -2189,10 +1768,8 @@ async def test_list_product_sets_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_product_sets), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductSetsResponse( @@ -2201,17 +1778,17 @@ async def test_list_product_sets_async_pages(): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -2224,22 +1801,18 @@ async def test_list_product_sets_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_product_sets(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductSetRequest, - dict, - ], -) -def test_get_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductSetRequest, + dict, +]) +def test_get_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2250,11 +1823,13 @@ def test_get_product_set(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.get_product_set(request) @@ -2266,8 +1841,8 @@ def test_get_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_get_product_set_non_empty_request_with_auto_populated_field(): @@ -2275,29 +1850,28 @@ def test_get_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetProductSetRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetProductSetRequest( - name="name_value", + name='name_value', ) - def test_get_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2316,9 +1890,7 @@ def test_get_product_set_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product_set] = mock_rpc request = {} client.get_product_set(request) @@ -2332,11 +1904,8 @@ def test_get_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2350,17 +1919,12 @@ async def test_get_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_product_set] = mock_rpc request = {} await client.get_product_set(request) @@ -2374,12 +1938,8 @@ async def test_get_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetProductSetRequest, -): +async def test_get_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2390,14 +1950,14 @@ async def test_get_product_set_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.get_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2408,15 +1968,14 @@ async def test_get_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_get_product_set_async_from_dict(): await test_get_product_set_async(request_type=dict) - def test_get_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2426,10 +1985,12 @@ def test_get_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.get_product_set(request) @@ -2441,9 +2002,9 @@ def test_get_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2456,13 +2017,13 @@ async def test_get_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.get_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2473,9 +2034,9 @@ async def test_get_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_product_set_flattened(): @@ -2484,13 +2045,15 @@ def test_get_product_set_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -2498,7 +2061,7 @@ def test_get_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -2512,10 +2075,9 @@ def test_get_product_set_flattened_error(): with pytest.raises(ValueError): client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -2523,17 +2085,17 @@ async def test_get_product_set_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -2541,10 +2103,9 @@ async def test_get_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2556,18 +2117,15 @@ async def test_get_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductSetRequest, - dict, - ], -) -def test_update_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductSetRequest, + dict, +]) +def test_update_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2579,12 +2137,12 @@ def test_update_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) response = client.update_product_set(request) @@ -2596,8 +2154,8 @@ def test_update_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' def test_update_product_set_non_empty_request_with_auto_populated_field(): @@ -2605,26 +2163,25 @@ def test_update_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = product_search_service.UpdateProductSetRequest() + request = product_search_service.UpdateProductSetRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.update_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.update_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductSetRequest() - + assert args[0] == product_search_service.UpdateProductSetRequest( + ) def test_update_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2640,18 +2197,12 @@ def test_update_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_product_set in client._transport._wrapped_methods - ) + assert client._transport.update_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_product_set] = mock_rpc request = {} client.update_product_set(request) @@ -2664,11 +2215,8 @@ def test_update_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_update_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2682,17 +2230,12 @@ async def test_update_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.update_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.update_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.update_product_set] = mock_rpc request = {} await client.update_product_set(request) @@ -2706,12 +2249,8 @@ async def test_update_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.UpdateProductSetRequest, -): +async def test_update_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.UpdateProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2723,15 +2262,13 @@ async def test_update_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) response = await client.update_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2742,15 +2279,14 @@ async def test_update_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.asyncio async def test_update_product_set_async_from_dict(): await test_update_product_set_async(request_type=dict) - def test_update_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2760,12 +2296,12 @@ def test_update_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductSetRequest() - request.product_set.name = "name_value" + request.product_set.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.update_product_set(request) @@ -2777,9 +2313,9 @@ def test_update_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product_set.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product_set.name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2792,15 +2328,13 @@ async def test_update_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductSetRequest() - request.product_set.name = "name_value" + request.product_set.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + type(client.transport.update_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) await client.update_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -2811,9 +2345,9 @@ async def test_update_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product_set.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product_set.name=name_value', + ) in kw['metadata'] def test_update_product_set_flattened(): @@ -2823,15 +2357,15 @@ def test_update_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_product_set( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -2839,10 +2373,10 @@ def test_update_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val @@ -2856,11 +2390,10 @@ def test_update_product_set_flattened_error(): with pytest.raises(ValueError): client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) - @pytest.mark.asyncio async def test_update_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -2869,19 +2402,17 @@ async def test_update_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ProductSet() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_product_set( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -2889,13 +2420,12 @@ async def test_update_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].product_set - mock_val = product_search_service.ProductSet(name="name_value") + mock_val = product_search_service.ProductSet(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val - @pytest.mark.asyncio async def test_update_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -2907,19 +2437,16 @@ async def test_update_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductSetRequest, - dict, - ], -) -def test_delete_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductSetRequest, + dict, +]) +def test_delete_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2931,8 +2458,8 @@ def test_delete_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_product_set(request) @@ -2952,31 +2479,28 @@ def test_delete_product_set_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteProductSetRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.delete_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteProductSetRequest( - name="name_value", + name='name_value', ) - def test_delete_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2991,18 +2515,12 @@ def test_delete_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_product_set in client._transport._wrapped_methods - ) + assert client._transport.delete_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_set] = mock_rpc request = {} client.delete_product_set(request) @@ -3015,11 +2533,8 @@ def test_delete_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3033,17 +2548,12 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_product_set] = mock_rpc request = {} await client.delete_product_set(request) @@ -3057,12 +2567,8 @@ async def test_delete_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteProductSetRequest, -): +async def test_delete_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3074,8 +2580,8 @@ async def test_delete_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_product_set(request) @@ -3094,7 +2600,6 @@ async def test_delete_product_set_async( async def test_delete_product_set_async_from_dict(): await test_delete_product_set_async(request_type=dict) - def test_delete_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3104,12 +2609,12 @@ def test_delete_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = None client.delete_product_set(request) @@ -3121,9 +2626,9 @@ def test_delete_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3136,12 +2641,12 @@ async def test_delete_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product_set(request) @@ -3153,9 +2658,9 @@ async def test_delete_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_product_set_flattened(): @@ -3165,14 +2670,14 @@ def test_delete_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -3180,7 +2685,7 @@ def test_delete_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -3194,10 +2699,9 @@ def test_delete_product_set_flattened_error(): with pytest.raises(ValueError): client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -3206,8 +2710,8 @@ async def test_delete_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -3215,7 +2719,7 @@ async def test_delete_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -3223,10 +2727,9 @@ async def test_delete_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3238,18 +2741,15 @@ async def test_delete_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductRequest, - dict, - ], -) -def test_create_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductRequest, + dict, +]) +def test_create_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3260,13 +2760,15 @@ def test_create_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.create_product(request) @@ -3278,10 +2780,10 @@ def test_create_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_create_product_non_empty_request_with_auto_populated_field(): @@ -3289,31 +2791,30 @@ def test_create_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateProductRequest( - parent="parent_value", - product_id="product_id_value", + parent='parent_value', + product_id='product_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateProductRequest( - parent="parent_value", - product_id="product_id_value", + parent='parent_value', + product_id='product_id_value', ) - def test_create_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3332,9 +2833,7 @@ def test_create_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.create_product] = mock_rpc request = {} client.create_product(request) @@ -3348,11 +2847,8 @@ def test_create_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3366,17 +2862,12 @@ async def test_create_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_product] = mock_rpc request = {} await client.create_product(request) @@ -3390,12 +2881,8 @@ async def test_create_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateProductRequest, -): +async def test_create_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3406,16 +2893,16 @@ async def test_create_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.create_product(request) # Establish that the underlying gRPC stub method was called. @@ -3426,17 +2913,16 @@ async def test_create_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_create_product_async_from_dict(): await test_create_product_async(request_type=dict) - def test_create_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3446,10 +2932,12 @@ def test_create_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: call.return_value = product_search_service.Product() client.create_product(request) @@ -3461,9 +2949,9 @@ def test_create_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3476,13 +2964,13 @@ async def test_create_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateProductRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.create_product(request) # Establish that the underlying gRPC stub method was called. @@ -3493,9 +2981,9 @@ async def test_create_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_product_flattened(): @@ -3504,15 +2992,17 @@ def test_create_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_product( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) # Establish that the underlying call was made with the expected @@ -3520,13 +3010,13 @@ def test_create_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].product_id - mock_val = "product_id_value" + mock_val = 'product_id_value' assert arg == mock_val @@ -3540,12 +3030,11 @@ def test_create_product_flattened_error(): with pytest.raises(ValueError): client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) - @pytest.mark.asyncio async def test_create_product_flattened_async(): client = ProductSearchAsyncClient( @@ -3553,19 +3042,19 @@ async def test_create_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_product( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) # Establish that the underlying call was made with the expected @@ -3573,16 +3062,15 @@ async def test_create_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].product_id - mock_val = "product_id_value" + mock_val = 'product_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3594,20 +3082,17 @@ async def test_create_product_flattened_error_async(): with pytest.raises(ValueError): await client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsRequest, - dict, - ], -) -def test_list_products(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsRequest, + dict, +]) +def test_list_products(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3618,10 +3103,12 @@ def test_list_products(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_products(request) @@ -3633,7 +3120,7 @@ def test_list_products(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_products_non_empty_request_with_auto_populated_field(): @@ -3641,31 +3128,30 @@ def test_list_products_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_products(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductsRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_products_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3684,9 +3170,7 @@ def test_list_products_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} client.list_products(request) @@ -3700,11 +3184,8 @@ def test_list_products_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3718,17 +3199,12 @@ async def test_list_products_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_products - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_products in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_products - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_products] = mock_rpc request = {} await client.list_products(request) @@ -3742,12 +3218,8 @@ async def test_list_products_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductsRequest, -): +async def test_list_products_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3758,13 +3230,13 @@ async def test_list_products_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) response = await client.list_products(request) # Establish that the underlying gRPC stub method was called. @@ -3775,14 +3247,13 @@ async def test_list_products_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_products_async_from_dict(): await test_list_products_async(request_type=dict) - def test_list_products_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3792,10 +3263,12 @@ def test_list_products_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: call.return_value = product_search_service.ListProductsResponse() client.list_products(request) @@ -3807,9 +3280,9 @@ def test_list_products_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -3822,13 +3295,13 @@ async def test_list_products_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse() - ) + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse()) await client.list_products(request) # Establish that the underlying gRPC stub method was called. @@ -3839,9 +3312,9 @@ async def test_list_products_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_products_flattened(): @@ -3850,13 +3323,15 @@ def test_list_products_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -3864,7 +3339,7 @@ def test_list_products_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -3878,10 +3353,9 @@ def test_list_products_flattened_error(): with pytest.raises(ValueError): client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_products_flattened_async(): client = ProductSearchAsyncClient( @@ -3889,17 +3363,17 @@ async def test_list_products_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -3907,10 +3381,9 @@ async def test_list_products_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_products_flattened_error_async(): client = ProductSearchAsyncClient( @@ -3922,7 +3395,7 @@ async def test_list_products_flattened_error_async(): with pytest.raises(ValueError): await client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -3933,7 +3406,9 @@ def test_list_products_pager(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -3942,17 +3417,17 @@ def test_list_products_pager(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -3967,7 +3442,9 @@ def test_list_products_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_products(request={}, retry=retry, timeout=timeout) @@ -3977,9 +3454,8 @@ def test_list_products_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) - - + assert all(isinstance(i, product_search_service.Product) + for i in results) def test_list_products_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3987,7 +3463,9 @@ def test_list_products_pages(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -3996,17 +3474,17 @@ def test_list_products_pages(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4017,10 +3495,9 @@ def test_list_products_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_products(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_products_async_pager(): client = ProductSearchAsyncClient( @@ -4029,8 +3506,8 @@ async def test_list_products_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products), "__call__", new_callable=mock.AsyncMock - ) as call: + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -4039,17 +3516,17 @@ async def test_list_products_async_pager(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4059,16 +3536,15 @@ async def test_list_products_async_pager(): ), RuntimeError, ) - async_pager = await client.list_products( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_products(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.Product) for i in responses) + assert all(isinstance(i, product_search_service.Product) + for i in responses) @pytest.mark.asyncio @@ -4079,8 +3555,8 @@ async def test_list_products_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products), "__call__", new_callable=mock.AsyncMock - ) as call: + type(client.transport.list_products), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsResponse( @@ -4089,17 +3565,17 @@ async def test_list_products_async_pages(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -4112,22 +3588,18 @@ async def test_list_products_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_products(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductRequest, - dict, - ], -) -def test_get_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductRequest, + dict, +]) +def test_get_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4138,13 +3610,15 @@ def test_get_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.get_product(request) @@ -4156,10 +3630,10 @@ def test_get_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_get_product_non_empty_request_with_auto_populated_field(): @@ -4167,29 +3641,28 @@ def test_get_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetProductRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetProductRequest( - name="name_value", + name='name_value', ) - def test_get_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4208,9 +3681,7 @@ def test_get_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product] = mock_rpc request = {} client.get_product(request) @@ -4224,11 +3695,8 @@ def test_get_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4242,17 +3710,12 @@ async def test_get_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_product] = mock_rpc request = {} await client.get_product(request) @@ -4266,12 +3729,8 @@ async def test_get_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetProductRequest, -): +async def test_get_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4282,16 +3741,16 @@ async def test_get_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.get_product(request) # Establish that the underlying gRPC stub method was called. @@ -4302,17 +3761,16 @@ async def test_get_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_get_product_async_from_dict(): await test_get_product_async(request_type=dict) - def test_get_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4322,10 +3780,12 @@ def test_get_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: call.return_value = product_search_service.Product() client.get_product(request) @@ -4337,9 +3797,9 @@ def test_get_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -4352,13 +3812,13 @@ async def test_get_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.get_product(request) # Establish that the underlying gRPC stub method was called. @@ -4369,9 +3829,9 @@ async def test_get_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_product_flattened(): @@ -4380,13 +3840,15 @@ def test_get_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -4394,7 +3856,7 @@ def test_get_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -4408,10 +3870,9 @@ def test_get_product_flattened_error(): with pytest.raises(ValueError): client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_product_flattened_async(): client = ProductSearchAsyncClient( @@ -4419,17 +3880,17 @@ async def test_get_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -4437,10 +3898,9 @@ async def test_get_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -4452,18 +3912,15 @@ async def test_get_product_flattened_error_async(): with pytest.raises(ValueError): await client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductRequest, - dict, - ], -) -def test_update_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductRequest, + dict, +]) +def test_update_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4474,13 +3931,15 @@ def test_update_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) response = client.update_product(request) @@ -4492,10 +3951,10 @@ def test_update_product(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' def test_update_product_non_empty_request_with_auto_populated_field(): @@ -4503,24 +3962,25 @@ def test_update_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = product_search_service.UpdateProductRequest() + request = product_search_service.UpdateProductRequest( + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.update_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductRequest() - + assert args[0] == product_search_service.UpdateProductRequest( + ) def test_update_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4540,9 +4000,7 @@ def test_update_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} client.update_product(request) @@ -4556,11 +4014,8 @@ def test_update_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_update_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4574,17 +4029,12 @@ async def test_update_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.update_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.update_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.update_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.update_product] = mock_rpc request = {} await client.update_product(request) @@ -4598,12 +4048,8 @@ async def test_update_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_update_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.UpdateProductRequest, -): +async def test_update_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.UpdateProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4614,16 +4060,16 @@ async def test_update_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) response = await client.update_product(request) # Establish that the underlying gRPC stub method was called. @@ -4634,17 +4080,16 @@ async def test_update_product_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.asyncio async def test_update_product_async_from_dict(): await test_update_product_async(request_type=dict) - def test_update_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4654,10 +4099,12 @@ def test_update_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductRequest() - request.product.name = "name_value" + request.product.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: call.return_value = product_search_service.Product() client.update_product(request) @@ -4669,9 +4116,9 @@ def test_update_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -4684,13 +4131,13 @@ async def test_update_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.UpdateProductRequest() - request.product.name = "name_value" + request.product.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) await client.update_product(request) # Establish that the underlying gRPC stub method was called. @@ -4701,9 +4148,9 @@ async def test_update_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "product.name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'product.name=name_value', + ) in kw['metadata'] def test_update_product_flattened(): @@ -4712,14 +4159,16 @@ def test_update_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_product( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -4727,10 +4176,10 @@ def test_update_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val @@ -4744,11 +4193,10 @@ def test_update_product_flattened_error(): with pytest.raises(ValueError): client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) - @pytest.mark.asyncio async def test_update_product_flattened_async(): client = ProductSearchAsyncClient( @@ -4756,18 +4204,18 @@ async def test_update_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.Product() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_product( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) # Establish that the underlying call was made with the expected @@ -4775,13 +4223,12 @@ async def test_update_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].product - mock_val = product_search_service.Product(name="name_value") + mock_val = product_search_service.Product(name='name_value') assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) assert arg == mock_val - @pytest.mark.asyncio async def test_update_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -4793,19 +4240,16 @@ async def test_update_product_flattened_error_async(): with pytest.raises(ValueError): await client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductRequest, - dict, - ], -) -def test_delete_product(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductRequest, + dict, +]) +def test_delete_product(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4816,7 +4260,9 @@ def test_delete_product(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_product(request) @@ -4836,29 +4282,28 @@ def test_delete_product_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteProductRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_product(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteProductRequest( - name="name_value", + name='name_value', ) - def test_delete_product_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4877,9 +4322,7 @@ def test_delete_product_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc request = {} client.delete_product(request) @@ -4893,11 +4336,8 @@ def test_delete_product_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_product_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -4911,17 +4351,12 @@ async def test_delete_product_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_product - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_product in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_product - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_product] = mock_rpc request = {} await client.delete_product(request) @@ -4935,12 +4370,8 @@ async def test_delete_product_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_product_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteProductRequest, -): +async def test_delete_product_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteProductRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4951,7 +4382,9 @@ async def test_delete_product_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_product(request) @@ -4970,7 +4403,6 @@ async def test_delete_product_async( async def test_delete_product_async_from_dict(): await test_delete_product_async(request_type=dict) - def test_delete_product_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4980,10 +4412,12 @@ def test_delete_product_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = None client.delete_product(request) @@ -4995,9 +4429,9 @@ def test_delete_product_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5010,10 +4444,12 @@ async def test_delete_product_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteProductRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product(request) @@ -5025,9 +4461,9 @@ async def test_delete_product_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_product_flattened(): @@ -5036,13 +4472,15 @@ def test_delete_product_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5050,7 +4488,7 @@ def test_delete_product_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -5064,10 +4502,9 @@ def test_delete_product_flattened_error(): with pytest.raises(ValueError): client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_product_flattened_async(): client = ProductSearchAsyncClient( @@ -5075,7 +4512,9 @@ async def test_delete_product_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -5083,7 +4522,7 @@ async def test_delete_product_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_product( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5091,10 +4530,9 @@ async def test_delete_product_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_product_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5106,18 +4544,15 @@ async def test_delete_product_flattened_error_async(): with pytest.raises(ValueError): await client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateReferenceImageRequest, - dict, - ], -) -def test_create_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateReferenceImageRequest, + dict, +]) +def test_create_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5129,12 +4564,12 @@ def test_create_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) response = client.create_reference_image(request) @@ -5146,8 +4581,8 @@ def test_create_reference_image(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' def test_create_reference_image_non_empty_request_with_auto_populated_field(): @@ -5155,33 +4590,30 @@ def test_create_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.CreateReferenceImageRequest( - parent="parent_value", - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image_id='reference_image_id_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.create_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.create_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.CreateReferenceImageRequest( - parent="parent_value", - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image_id='reference_image_id_value', ) - def test_create_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5196,19 +4628,12 @@ def test_create_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.create_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_reference_image] = mock_rpc request = {} client.create_reference_image(request) @@ -5221,11 +4646,8 @@ def test_create_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_create_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5239,17 +4661,12 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.create_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.create_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.create_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.create_reference_image] = mock_rpc request = {} await client.create_reference_image(request) @@ -5263,12 +4680,8 @@ async def test_create_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_create_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.CreateReferenceImageRequest, -): +async def test_create_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.CreateReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5280,15 +4693,13 @@ async def test_create_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) response = await client.create_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -5299,15 +4710,14 @@ async def test_create_reference_image_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.asyncio async def test_create_reference_image_async_from_dict(): await test_create_reference_image_async(request_type=dict) - def test_create_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5317,12 +4727,12 @@ def test_create_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.CreateReferenceImageRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.create_reference_image(request) @@ -5334,9 +4744,9 @@ def test_create_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5349,15 +4759,13 @@ async def test_create_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.CreateReferenceImageRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + type(client.transport.create_reference_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) await client.create_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -5368,9 +4776,9 @@ async def test_create_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_create_reference_image_flattened(): @@ -5380,16 +4788,16 @@ def test_create_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_reference_image( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) # Establish that the underlying call was made with the expected @@ -5397,13 +4805,13 @@ def test_create_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].reference_image - mock_val = product_search_service.ReferenceImage(name="name_value") + mock_val = product_search_service.ReferenceImage(name='name_value') assert arg == mock_val arg = args[0].reference_image_id - mock_val = "reference_image_id_value" + mock_val = 'reference_image_id_value' assert arg == mock_val @@ -5417,12 +4825,11 @@ def test_create_reference_image_flattened_error(): with pytest.raises(ValueError): client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) - @pytest.mark.asyncio async def test_create_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -5431,20 +4838,18 @@ async def test_create_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_reference_image( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) # Establish that the underlying call was made with the expected @@ -5452,16 +4857,15 @@ async def test_create_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].reference_image - mock_val = product_search_service.ReferenceImage(name="name_value") + mock_val = product_search_service.ReferenceImage(name='name_value') assert arg == mock_val arg = args[0].reference_image_id - mock_val = "reference_image_id_value" + mock_val = 'reference_image_id_value' assert arg == mock_val - @pytest.mark.asyncio async def test_create_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5473,20 +4877,17 @@ async def test_create_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteReferenceImageRequest, - dict, - ], -) -def test_delete_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteReferenceImageRequest, + dict, +]) +def test_delete_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5498,8 +4899,8 @@ def test_delete_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_reference_image(request) @@ -5519,31 +4920,28 @@ def test_delete_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.DeleteReferenceImageRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.delete_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.delete_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.DeleteReferenceImageRequest( - name="name_value", + name='name_value', ) - def test_delete_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5558,19 +4956,12 @@ def test_delete_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.delete_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_reference_image] = mock_rpc request = {} client.delete_reference_image(request) @@ -5583,11 +4974,8 @@ def test_delete_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_delete_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5601,17 +4989,12 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.delete_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.delete_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.delete_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.delete_reference_image] = mock_rpc request = {} await client.delete_reference_image(request) @@ -5625,12 +5008,8 @@ async def test_delete_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_delete_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.DeleteReferenceImageRequest, -): +async def test_delete_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.DeleteReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5642,8 +5021,8 @@ async def test_delete_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_reference_image(request) @@ -5662,7 +5041,6 @@ async def test_delete_reference_image_async( async def test_delete_reference_image_async_from_dict(): await test_delete_reference_image_async(request_type=dict) - def test_delete_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5672,12 +5050,12 @@ def test_delete_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = None client.delete_reference_image(request) @@ -5689,9 +5067,9 @@ def test_delete_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -5704,12 +5082,12 @@ async def test_delete_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.DeleteReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_reference_image(request) @@ -5721,9 +5099,9 @@ async def test_delete_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_delete_reference_image_flattened(): @@ -5733,14 +5111,14 @@ def test_delete_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5748,7 +5126,7 @@ def test_delete_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -5762,10 +5140,9 @@ def test_delete_reference_image_flattened_error(): with pytest.raises(ValueError): client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_delete_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -5774,8 +5151,8 @@ async def test_delete_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -5783,7 +5160,7 @@ async def test_delete_reference_image_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -5791,10 +5168,9 @@ async def test_delete_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_delete_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -5806,18 +5182,15 @@ async def test_delete_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListReferenceImagesRequest, - dict, - ], -) -def test_list_reference_images(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListReferenceImagesRequest, + dict, +]) +def test_list_reference_images(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5829,12 +5202,12 @@ def test_list_reference_images(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse( page_size=951, - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_reference_images(request) @@ -5847,7 +5220,7 @@ def test_list_reference_images(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_reference_images_non_empty_request_with_auto_populated_field(): @@ -5855,33 +5228,30 @@ def test_list_reference_images_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListReferenceImagesRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_reference_images), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_reference_images(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListReferenceImagesRequest( - parent="parent_value", - page_token="page_token_value", + parent='parent_value', + page_token='page_token_value', ) - def test_list_reference_images_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5896,19 +5266,12 @@ def test_list_reference_images_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_reference_images - in client._transport._wrapped_methods - ) + assert client._transport.list_reference_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reference_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_reference_images] = mock_rpc request = {} client.list_reference_images(request) @@ -5921,11 +5284,8 @@ def test_list_reference_images_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_reference_images_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_reference_images_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -5939,17 +5299,12 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_reference_images - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_reference_images in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_reference_images - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_reference_images] = mock_rpc request = {} await client.list_reference_images(request) @@ -5963,12 +5318,8 @@ async def test_list_reference_images_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_reference_images_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListReferenceImagesRequest, -): +async def test_list_reference_images_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListReferenceImagesRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5980,15 +5331,13 @@ async def test_list_reference_images_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse( + page_size=951, + next_page_token='next_page_token_value', + )) response = await client.list_reference_images(request) # Establish that the underlying gRPC stub method was called. @@ -6000,14 +5349,13 @@ async def test_list_reference_images_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesAsyncPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_reference_images_async_from_dict(): await test_list_reference_images_async(request_type=dict) - def test_list_reference_images_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6017,12 +5365,12 @@ def test_list_reference_images_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListReferenceImagesRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: call.return_value = product_search_service.ListReferenceImagesResponse() client.list_reference_images(request) @@ -6034,9 +5382,9 @@ def test_list_reference_images_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6049,15 +5397,13 @@ async def test_list_reference_images_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListReferenceImagesRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse() - ) + type(client.transport.list_reference_images), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse()) await client.list_reference_images(request) # Establish that the underlying gRPC stub method was called. @@ -6068,9 +5414,9 @@ async def test_list_reference_images_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_list_reference_images_flattened(): @@ -6080,14 +5426,14 @@ def test_list_reference_images_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_reference_images( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -6095,7 +5441,7 @@ def test_list_reference_images_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -6109,10 +5455,9 @@ def test_list_reference_images_flattened_error(): with pytest.raises(ValueError): client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_list_reference_images_flattened_async(): client = ProductSearchAsyncClient( @@ -6121,18 +5466,16 @@ async def test_list_reference_images_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListReferenceImagesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_reference_images( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -6140,10 +5483,9 @@ async def test_list_reference_images_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_reference_images_flattened_error_async(): client = ProductSearchAsyncClient( @@ -6155,7 +5497,7 @@ async def test_list_reference_images_flattened_error_async(): with pytest.raises(ValueError): await client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) @@ -6167,8 +5509,8 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6177,17 +5519,17 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6202,7 +5544,9 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), ) pager = client.list_reference_images(request={}, retry=retry, timeout=timeout) @@ -6212,11 +5556,8 @@ def test_list_reference_images_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in results - ) - - + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in results) def test_list_reference_images_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6225,8 +5566,8 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6235,17 +5576,17 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6256,10 +5597,9 @@ def test_list_reference_images_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_reference_images(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_reference_images_async_pager(): client = ProductSearchAsyncClient( @@ -6268,10 +5608,8 @@ async def test_list_reference_images_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_reference_images), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6280,17 +5618,17 @@ async def test_list_reference_images_async_pager(): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6300,18 +5638,15 @@ async def test_list_reference_images_async_pager(): ), RuntimeError, ) - async_pager = await client.list_reference_images( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_reference_images(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in responses - ) + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in responses) @pytest.mark.asyncio @@ -6322,10 +5657,8 @@ async def test_list_reference_images_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_reference_images), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListReferenceImagesResponse( @@ -6334,17 +5667,17 @@ async def test_list_reference_images_async_pages(): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -6357,22 +5690,18 @@ async def test_list_reference_images_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_reference_images(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetReferenceImageRequest, - dict, - ], -) -def test_get_reference_image(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.GetReferenceImageRequest, + dict, +]) +def test_get_reference_image(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6384,12 +5713,12 @@ def test_get_reference_image(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) response = client.get_reference_image(request) @@ -6401,8 +5730,8 @@ def test_get_reference_image(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' def test_get_reference_image_non_empty_request_with_auto_populated_field(): @@ -6410,31 +5739,28 @@ def test_get_reference_image_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.GetReferenceImageRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.get_reference_image), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.get_reference_image(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.GetReferenceImageRequest( - name="name_value", + name='name_value', ) - def test_get_reference_image_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6449,18 +5775,12 @@ def test_get_reference_image_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_reference_image in client._transport._wrapped_methods - ) + assert client._transport.get_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_reference_image] = mock_rpc request = {} client.get_reference_image(request) @@ -6473,11 +5793,8 @@ def test_get_reference_image_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_reference_image_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_reference_image_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -6491,17 +5808,12 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.get_reference_image - in client._client._transport._wrapped_methods - ) + assert client._client._transport.get_reference_image in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.get_reference_image - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.get_reference_image] = mock_rpc request = {} await client.get_reference_image(request) @@ -6515,12 +5827,8 @@ async def test_get_reference_image_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_get_reference_image_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.GetReferenceImageRequest, -): +async def test_get_reference_image_async(transport: str = 'grpc_asyncio', request_type=product_search_service.GetReferenceImageRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6532,15 +5840,13 @@ async def test_get_reference_image_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) response = await client.get_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -6551,15 +5857,14 @@ async def test_get_reference_image_async( # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.asyncio async def test_get_reference_image_async_from_dict(): await test_get_reference_image_async(request_type=dict) - def test_get_reference_image_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6569,12 +5874,12 @@ def test_get_reference_image_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.GetReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.get_reference_image(request) @@ -6586,9 +5891,9 @@ def test_get_reference_image_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6601,15 +5906,13 @@ async def test_get_reference_image_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.GetReferenceImageRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + type(client.transport.get_reference_image), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) await client.get_reference_image(request) # Establish that the underlying gRPC stub method was called. @@ -6620,9 +5923,9 @@ async def test_get_reference_image_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_get_reference_image_flattened(): @@ -6632,14 +5935,14 @@ def test_get_reference_image_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -6647,7 +5950,7 @@ def test_get_reference_image_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -6661,10 +5964,9 @@ def test_get_reference_image_flattened_error(): with pytest.raises(ValueError): client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_get_reference_image_flattened_async(): client = ProductSearchAsyncClient( @@ -6673,18 +5975,16 @@ async def test_get_reference_image_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ReferenceImage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_reference_image( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -6692,10 +5992,9 @@ async def test_get_reference_image_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_get_reference_image_flattened_error_async(): client = ProductSearchAsyncClient( @@ -6707,18 +6006,15 @@ async def test_get_reference_image_flattened_error_async(): with pytest.raises(ValueError): await client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.AddProductToProductSetRequest, - dict, - ], -) -def test_add_product_to_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.AddProductToProductSetRequest, + dict, +]) +def test_add_product_to_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6730,8 +6026,8 @@ def test_add_product_to_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.add_product_to_product_set(request) @@ -6751,33 +6047,30 @@ def test_add_product_to_product_set_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.AddProductToProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.add_product_to_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.add_product_to_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.AddProductToProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - def test_add_product_to_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6792,19 +6085,12 @@ def test_add_product_to_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.add_product_to_product_set - in client._transport._wrapped_methods - ) + assert client._transport.add_product_to_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_product_to_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_product_to_product_set] = mock_rpc request = {} client.add_product_to_product_set(request) @@ -6817,11 +6103,8 @@ def test_add_product_to_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_add_product_to_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -6835,17 +6118,12 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.add_product_to_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.add_product_to_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.add_product_to_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.add_product_to_product_set] = mock_rpc request = {} await client.add_product_to_product_set(request) @@ -6859,12 +6137,8 @@ async def test_add_product_to_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_add_product_to_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.AddProductToProductSetRequest, -): +async def test_add_product_to_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.AddProductToProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6876,8 +6150,8 @@ async def test_add_product_to_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.add_product_to_product_set(request) @@ -6896,7 +6170,6 @@ async def test_add_product_to_product_set_async( async def test_add_product_to_product_set_async_from_dict(): await test_add_product_to_product_set_async(request_type=dict) - def test_add_product_to_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6906,12 +6179,12 @@ def test_add_product_to_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.AddProductToProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = None client.add_product_to_product_set(request) @@ -6923,9 +6196,9 @@ def test_add_product_to_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -6938,12 +6211,12 @@ async def test_add_product_to_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.AddProductToProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.add_product_to_product_set(request) @@ -6955,9 +6228,9 @@ async def test_add_product_to_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_add_product_to_product_set_flattened(): @@ -6967,15 +6240,15 @@ def test_add_product_to_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.add_product_to_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -6983,10 +6256,10 @@ def test_add_product_to_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val @@ -7000,11 +6273,10 @@ def test_add_product_to_product_set_flattened_error(): with pytest.raises(ValueError): client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7013,8 +6285,8 @@ async def test_add_product_to_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -7022,8 +6294,8 @@ async def test_add_product_to_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.add_product_to_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7031,13 +6303,12 @@ async def test_add_product_to_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val - @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7049,19 +6320,16 @@ async def test_add_product_to_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.RemoveProductFromProductSetRequest, - dict, - ], -) -def test_remove_product_from_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.RemoveProductFromProductSetRequest, + dict, +]) +def test_remove_product_from_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7073,8 +6341,8 @@ def test_remove_product_from_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None response = client.remove_product_from_product_set(request) @@ -7094,33 +6362,30 @@ def test_remove_product_from_product_set_non_empty_request_with_auto_populated_f # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.RemoveProductFromProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.remove_product_from_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.remove_product_from_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.RemoveProductFromProductSetRequest( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - def test_remove_product_from_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7135,19 +6400,12 @@ def test_remove_product_from_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.remove_product_from_product_set - in client._transport._wrapped_methods - ) + assert client._transport.remove_product_from_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_product_from_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_product_from_product_set] = mock_rpc request = {} client.remove_product_from_product_set(request) @@ -7160,11 +6418,8 @@ def test_remove_product_from_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7178,17 +6433,12 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.remove_product_from_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.remove_product_from_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.remove_product_from_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.remove_product_from_product_set] = mock_rpc request = {} await client.remove_product_from_product_set(request) @@ -7202,12 +6452,8 @@ async def test_remove_product_from_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_remove_product_from_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +async def test_remove_product_from_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.RemoveProductFromProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7219,8 +6465,8 @@ async def test_remove_product_from_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.remove_product_from_product_set(request) @@ -7239,7 +6485,6 @@ async def test_remove_product_from_product_set_async( async def test_remove_product_from_product_set_async_from_dict(): await test_remove_product_from_product_set_async(request_type=dict) - def test_remove_product_from_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7249,12 +6494,12 @@ def test_remove_product_from_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.RemoveProductFromProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = None client.remove_product_from_product_set(request) @@ -7266,9 +6511,9 @@ def test_remove_product_from_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -7281,12 +6526,12 @@ async def test_remove_product_from_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.RemoveProductFromProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.remove_product_from_product_set(request) @@ -7298,9 +6543,9 @@ async def test_remove_product_from_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_remove_product_from_product_set_flattened(): @@ -7310,15 +6555,15 @@ def test_remove_product_from_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.remove_product_from_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7326,10 +6571,10 @@ def test_remove_product_from_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val @@ -7343,11 +6588,10 @@ def test_remove_product_from_product_set_flattened_error(): with pytest.raises(ValueError): client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) - @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7356,8 +6600,8 @@ async def test_remove_product_from_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = None @@ -7365,8 +6609,8 @@ async def test_remove_product_from_product_set_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.remove_product_from_product_set( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) # Establish that the underlying call was made with the expected @@ -7374,13 +6618,12 @@ async def test_remove_product_from_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].product - mock_val = "product_value" + mock_val = 'product_value' assert arg == mock_val - @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7392,19 +6635,16 @@ async def test_remove_product_from_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsInProductSetRequest, - dict, - ], -) -def test_list_products_in_product_set(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsInProductSetRequest, + dict, +]) +def test_list_products_in_product_set(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7416,11 +6656,11 @@ def test_list_products_in_product_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) response = client.list_products_in_product_set(request) @@ -7432,7 +6672,7 @@ def test_list_products_in_product_set(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' def test_list_products_in_product_set_non_empty_request_with_auto_populated_field(): @@ -7440,33 +6680,30 @@ def test_list_products_in_product_set_non_empty_request_with_auto_populated_fiel # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ListProductsInProductSetRequest( - name="name_value", - page_token="page_token_value", + name='name_value', + page_token='page_token_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.list_products_in_product_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.list_products_in_product_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ListProductsInProductSetRequest( - name="name_value", - page_token="page_token_value", + name='name_value', + page_token='page_token_value', ) - def test_list_products_in_product_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7481,19 +6718,12 @@ def test_list_products_in_product_set_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_products_in_product_set - in client._transport._wrapped_methods - ) + assert client._transport.list_products_in_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_products_in_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products_in_product_set] = mock_rpc request = {} client.list_products_in_product_set(request) @@ -7506,11 +6736,8 @@ def test_list_products_in_product_set_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_products_in_product_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7524,17 +6751,12 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.list_products_in_product_set - in client._client._transport._wrapped_methods - ) + assert client._client._transport.list_products_in_product_set in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.list_products_in_product_set - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.list_products_in_product_set] = mock_rpc request = {} await client.list_products_in_product_set(request) @@ -7548,12 +6770,8 @@ async def test_list_products_in_product_set_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_list_products_in_product_set_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ListProductsInProductSetRequest, -): +async def test_list_products_in_product_set_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ListProductsInProductSetRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7565,14 +6783,12 @@ async def test_list_products_in_product_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse( + next_page_token='next_page_token_value', + )) response = await client.list_products_in_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -7583,14 +6799,13 @@ async def test_list_products_in_product_set_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.asyncio async def test_list_products_in_product_set_async_from_dict(): await test_list_products_in_product_set_async(request_type=dict) - def test_list_products_in_product_set_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7600,12 +6815,12 @@ def test_list_products_in_product_set_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsInProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: call.return_value = product_search_service.ListProductsInProductSetResponse() client.list_products_in_product_set(request) @@ -7617,9 +6832,9 @@ def test_list_products_in_product_set_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -7632,15 +6847,13 @@ async def test_list_products_in_product_set_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ListProductsInProductSetRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse() - ) + type(client.transport.list_products_in_product_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse()) await client.list_products_in_product_set(request) # Establish that the underlying gRPC stub method was called. @@ -7651,9 +6864,9 @@ async def test_list_products_in_product_set_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_list_products_in_product_set_flattened(): @@ -7663,14 +6876,14 @@ def test_list_products_in_product_set_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_products_in_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -7678,7 +6891,7 @@ def test_list_products_in_product_set_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val @@ -7692,10 +6905,9 @@ def test_list_products_in_product_set_flattened_error(): with pytest.raises(ValueError): client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) - @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_async(): client = ProductSearchAsyncClient( @@ -7704,18 +6916,16 @@ async def test_list_products_in_product_set_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = product_search_service.ListProductsInProductSetResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_products_in_product_set( - name="name_value", + name='name_value', ) # Establish that the underlying call was made with the expected @@ -7723,10 +6933,9 @@ async def test_list_products_in_product_set_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val - @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_error_async(): client = ProductSearchAsyncClient( @@ -7738,7 +6947,7 @@ async def test_list_products_in_product_set_flattened_error_async(): with pytest.raises(ValueError): await client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) @@ -7750,8 +6959,8 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7760,17 +6969,17 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7785,11 +6994,11 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), - ) - pager = client.list_products_in_product_set( - request={}, retry=retry, timeout=timeout + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), ) + pager = client.list_products_in_product_set(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7797,9 +7006,8 @@ def test_list_products_in_product_set_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) - - + assert all(isinstance(i, product_search_service.Product) + for i in results) def test_list_products_in_product_set_pages(transport_name: str = "grpc"): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7808,8 +7016,8 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7818,17 +7026,17 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7839,10 +7047,9 @@ def test_list_products_in_product_set_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_products_in_product_set(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - @pytest.mark.asyncio async def test_list_products_in_product_set_async_pager(): client = ProductSearchAsyncClient( @@ -7851,10 +7058,8 @@ async def test_list_products_in_product_set_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_products_in_product_set), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7863,17 +7068,17 @@ async def test_list_products_in_product_set_async_pager(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7883,16 +7088,15 @@ async def test_list_products_in_product_set_async_pager(): ), RuntimeError, ) - async_pager = await client.list_products_in_product_set( - request={}, - ) - assert async_pager.next_page_token == "abc" + async_pager = await client.list_products_in_product_set(request={},) + assert async_pager.next_page_token == 'abc' responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, product_search_service.Product) for i in responses) + assert all(isinstance(i, product_search_service.Product) + for i in responses) @pytest.mark.asyncio @@ -7903,10 +7107,8 @@ async def test_list_products_in_product_set_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), - "__call__", - new_callable=mock.AsyncMock, - ) as call: + type(client.transport.list_products_in_product_set), + '__call__', new_callable=mock.AsyncMock) as call: # Set the response to a series of pages. call.side_effect = ( product_search_service.ListProductsInProductSetResponse( @@ -7915,17 +7117,17 @@ async def test_list_products_in_product_set_async_pages(): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -7938,22 +7140,18 @@ async def test_list_products_in_product_set_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_products_in_product_set(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ImportProductSetsRequest, - dict, - ], -) -def test_import_product_sets(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.ImportProductSetsRequest, + dict, +]) +def test_import_product_sets(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7965,10 +7163,10 @@ def test_import_product_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -7986,31 +7184,28 @@ def test_import_product_sets_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.ImportProductSetsRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.import_product_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.ImportProductSetsRequest( - parent="parent_value", + parent='parent_value', ) - def test_import_product_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8025,18 +7220,12 @@ def test_import_product_sets_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.import_product_sets in client._transport._wrapped_methods - ) + assert client._transport.import_product_sets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_product_sets] = mock_rpc request = {} client.import_product_sets(request) @@ -8054,11 +7243,8 @@ def test_import_product_sets_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_import_product_sets_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_import_product_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -8072,17 +7258,12 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.import_product_sets - in client._client._transport._wrapped_methods - ) + assert client._client._transport.import_product_sets in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.import_product_sets - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.import_product_sets] = mock_rpc request = {} await client.import_product_sets(request) @@ -8101,12 +7282,8 @@ async def test_import_product_sets_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_import_product_sets_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.ImportProductSetsRequest, -): +async def test_import_product_sets_async(transport: str = 'grpc_asyncio', request_type=product_search_service.ImportProductSetsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8118,11 +7295,11 @@ async def test_import_product_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.import_product_sets(request) @@ -8140,7 +7317,6 @@ async def test_import_product_sets_async( async def test_import_product_sets_async_from_dict(): await test_import_product_sets_async(request_type=dict) - def test_import_product_sets_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8150,13 +7326,13 @@ def test_import_product_sets_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.ImportProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -8167,9 +7343,9 @@ def test_import_product_sets_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -8182,15 +7358,13 @@ async def test_import_product_sets_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.ImportProductSetsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) await client.import_product_sets(request) # Establish that the underlying gRPC stub method was called. @@ -8201,9 +7375,9 @@ async def test_import_product_sets_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_import_product_sets_flattened(): @@ -8213,19 +7387,15 @@ def test_import_product_sets_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.import_product_sets( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) # Establish that the underlying call was made with the expected @@ -8233,14 +7403,10 @@ def test_import_product_sets_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].input_config - mock_val = product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ) + mock_val = product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')) assert arg == mock_val @@ -8254,15 +7420,10 @@ def test_import_product_sets_flattened_error(): with pytest.raises(ValueError): client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) - @pytest.mark.asyncio async def test_import_product_sets_flattened_async(): client = ProductSearchAsyncClient( @@ -8271,23 +7432,19 @@ async def test_import_product_sets_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.import_product_sets( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) # Establish that the underlying call was made with the expected @@ -8295,17 +7452,12 @@ async def test_import_product_sets_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val arg = args[0].input_config - mock_val = product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ) + mock_val = product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')) assert arg == mock_val - @pytest.mark.asyncio async def test_import_product_sets_flattened_error_async(): client = ProductSearchAsyncClient( @@ -8317,23 +7469,16 @@ async def test_import_product_sets_flattened_error_async(): with pytest.raises(ValueError): await client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.PurgeProductsRequest, - dict, - ], -) -def test_purge_products(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + product_search_service.PurgeProductsRequest, + dict, +]) +def test_purge_products(request_type, transport: str = 'grpc'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8344,9 +7489,11 @@ def test_purge_products(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name='operations/spam') response = client.purge_products(request) # Establish that the underlying gRPC stub method was called. @@ -8364,29 +7511,28 @@ def test_purge_products_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = product_search_service.PurgeProductsRequest( - parent="parent_value", + parent='parent_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.purge_products(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == product_search_service.PurgeProductsRequest( - parent="parent_value", + parent='parent_value', ) - def test_purge_products_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8405,9 +7551,7 @@ def test_purge_products_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.purge_products] = mock_rpc request = {} client.purge_products(request) @@ -8426,11 +7570,8 @@ def test_purge_products_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_purge_products_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_purge_products_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -8444,17 +7585,12 @@ async def test_purge_products_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.purge_products - in client._client._transport._wrapped_methods - ) + assert client._client._transport.purge_products in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.purge_products - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.purge_products] = mock_rpc request = {} await client.purge_products(request) @@ -8473,12 +7609,8 @@ async def test_purge_products_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_purge_products_async( - transport: str = "grpc_asyncio", - request_type=product_search_service.PurgeProductsRequest, -): +async def test_purge_products_async(transport: str = 'grpc_asyncio', request_type=product_search_service.PurgeProductsRequest): client = ProductSearchAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8489,10 +7621,12 @@ async def test_purge_products_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) response = await client.purge_products(request) @@ -8510,7 +7644,6 @@ async def test_purge_products_async( async def test_purge_products_async_from_dict(): await test_purge_products_async(request_type=dict) - def test_purge_products_field_headers(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8520,11 +7653,13 @@ def test_purge_products_field_headers(): # a field header. Set these to a non-empty value. request = product_search_service.PurgeProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.purge_products(request) # Establish that the underlying gRPC stub method was called. @@ -8535,9 +7670,9 @@ def test_purge_products_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -8550,13 +7685,13 @@ async def test_purge_products_field_headers_async(): # a field header. Set these to a non-empty value. request = product_search_service.PurgeProductsRequest() - request.parent = "parent_value" + request.parent = 'parent_value' - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) await client.purge_products(request) # Establish that the underlying gRPC stub method was called. @@ -8567,9 +7702,9 @@ async def test_purge_products_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] def test_purge_products_flattened(): @@ -8578,13 +7713,15 @@ def test_purge_products_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.purge_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -8592,7 +7729,7 @@ def test_purge_products_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val @@ -8606,10 +7743,9 @@ def test_purge_products_flattened_error(): with pytest.raises(ValueError): client.purge_products( product_search_service.PurgeProductsRequest(), - parent="parent_value", + parent='parent_value', ) - @pytest.mark.asyncio async def test_purge_products_flattened_async(): client = ProductSearchAsyncClient( @@ -8617,17 +7753,19 @@ async def test_purge_products_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = operations_pb2.Operation(name='operations/op') call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.purge_products( - parent="parent_value", + parent='parent_value', ) # Establish that the underlying call was made with the expected @@ -8635,10 +7773,9 @@ async def test_purge_products_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = "parent_value" + mock_val = 'parent_value' assert arg == mock_val - @pytest.mark.asyncio async def test_purge_products_flattened_error_async(): client = ProductSearchAsyncClient( @@ -8650,7 +7787,7 @@ async def test_purge_products_flattened_error_async(): with pytest.raises(ValueError): await client.purge_products( product_search_service.PurgeProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -8668,18 +7805,12 @@ def test_create_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_product_set in client._transport._wrapped_methods - ) + assert client._transport.create_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_product_set] = mock_rpc request = {} client.create_product_set(request) @@ -8694,64 +7825,59 @@ def test_create_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_product_set_rest_required_fields( - request_type=product_search_service.CreateProductSetRequest, -): +def test_create_product_set_rest_required_fields(request_type=product_search_service.CreateProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product_set._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("product_set_id",)) + assert not set(unset_fields) - set(("product_set_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -8761,32 +7887,24 @@ def test_create_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("productSetId",)) - & set( - ( - "parent", - "productSet", - ) - ) - ) + assert set(unset_fields) == (set(("productSetId", )) & set(("parent", "productSet", ))) def test_create_product_set_rest_flattened(): @@ -8796,18 +7914,18 @@ def test_create_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) mock_args.update(sample_request) @@ -8817,7 +7935,7 @@ def test_create_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -8827,14 +7945,10 @@ def test_create_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*}/productSets" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*}/productSets" % client.transport._host, args[1]) -def test_create_product_set_rest_flattened_error(transport: str = "rest"): +def test_create_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8845,9 +7959,9 @@ def test_create_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_product_set( product_search_service.CreateProductSetRequest(), - parent="parent_value", - product_set=product_search_service.ProductSet(name="name_value"), - product_set_id="product_set_id_value", + parent='parent_value', + product_set=product_search_service.ProductSet(name='name_value'), + product_set_id='product_set_id_value', ) @@ -8869,12 +7983,8 @@ def test_list_product_sets_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_product_sets] = mock_rpc request = {} client.list_product_sets(request) @@ -8889,67 +7999,57 @@ def test_list_product_sets_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_product_sets_rest_required_fields( - request_type=product_search_service.ListProductSetsRequest, -): +def test_list_product_sets_rest_required_fields(request_type=product_search_service.ListProductSetsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_product_sets._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_product_sets._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -8957,37 +8057,27 @@ def test_list_product_sets_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductSetsResponse.pb( - return_value - ) + return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_product_sets(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_product_sets_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_product_sets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_product_sets_rest_flattened(): @@ -8997,16 +8087,16 @@ def test_list_product_sets_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -9016,7 +8106,7 @@ def test_list_product_sets_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9026,14 +8116,10 @@ def test_list_product_sets_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*}/productSets" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*}/productSets" % client.transport._host, args[1]) -def test_list_product_sets_rest_flattened_error(transport: str = "rest"): +def test_list_product_sets_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9044,20 +8130,20 @@ def test_list_product_sets_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_product_sets( product_search_service.ListProductSetsRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_product_sets_rest_pager(transport: str = "rest"): +def test_list_product_sets_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductSetsResponse( @@ -9066,17 +8152,17 @@ def test_list_product_sets_rest_pager(transport: str = "rest"): product_search_service.ProductSet(), product_search_service.ProductSet(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductSetsResponse( product_sets=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductSetsResponse( product_sets=[ product_search_service.ProductSet(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductSetsResponse( product_sets=[ @@ -9089,25 +8175,24 @@ def test_list_product_sets_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductSetsResponse.to_json(x) for x in response - ) + response = tuple(product_search_service.ListProductSetsResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} pager = client.list_product_sets(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.ProductSet) for i in results) + assert all(isinstance(i, product_search_service.ProductSet) + for i in results) pages = list(client.list_product_sets(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -9129,9 +8214,7 @@ def test_get_product_set_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product_set] = mock_rpc request = {} @@ -9147,60 +8230,55 @@ def test_get_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_product_set_rest_required_fields( - request_type=product_search_service.GetProductSetRequest, -): +def test_get_product_set_rest_required_fields(request_type=product_search_service.GetProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -9211,24 +8289,24 @@ def test_get_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_product_set_rest_flattened(): @@ -9238,18 +8316,16 @@ def test_get_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -9259,7 +8335,7 @@ def test_get_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9269,14 +8345,10 @@ def test_get_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_get_product_set_rest_flattened_error(transport: str = "rest"): +def test_get_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9287,7 +8359,7 @@ def test_get_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_product_set( product_search_service.GetProductSetRequest(), - name="name_value", + name='name_value', ) @@ -9305,18 +8377,12 @@ def test_update_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_product_set in client._transport._wrapped_methods - ) + assert client._transport.update_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_product_set] = mock_rpc request = {} client.update_product_set(request) @@ -9331,59 +8397,54 @@ def test_update_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_product_set_rest_required_fields( - request_type=product_search_service.UpdateProductSetRequest, -): +def test_update_product_set_rest_required_fields(request_type=product_search_service.UpdateProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("update_mask", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9393,24 +8454,24 @@ def test_update_product_set_rest_required_fields( return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_update_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.update_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("productSet",))) + assert set(unset_fields) == (set(("updateMask", )) & set(("productSet", ))) def test_update_product_set_rest_flattened(): @@ -9420,21 +8481,17 @@ def test_update_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet() # get arguments that satisfy an http rule for this method - sample_request = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } + sample_request = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/sample3'}} # get truthy value for each flattened field mock_args = dict( - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) mock_args.update(sample_request) @@ -9444,7 +8501,7 @@ def test_update_product_set_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9454,14 +8511,10 @@ def test_update_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_update_product_set_rest_flattened_error(transport: str = "rest"): +def test_update_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9472,8 +8525,8 @@ def test_update_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.update_product_set( product_search_service.UpdateProductSetRequest(), - product_set=product_search_service.ProductSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product_set=product_search_service.ProductSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) @@ -9491,18 +8544,12 @@ def test_delete_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_product_set in client._transport._wrapped_methods - ) + assert client._transport.delete_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_product_set] = mock_rpc request = {} client.delete_product_set(request) @@ -9517,85 +8564,80 @@ def test_delete_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_product_set_rest_required_fields( - request_type=product_search_service.DeleteProductSetRequest, -): +def test_delete_product_set_rest_required_fields(request_type=product_search_service.DeleteProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_product_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_product_set_rest_flattened(): @@ -9605,26 +8647,24 @@ def test_delete_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9634,14 +8674,10 @@ def test_delete_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}" % client.transport._host, args[1]) -def test_delete_product_set_rest_flattened_error(transport: str = "rest"): +def test_delete_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9652,7 +8688,7 @@ def test_delete_product_set_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_product_set( product_search_service.DeleteProductSetRequest(), - name="name_value", + name='name_value', ) @@ -9674,9 +8710,7 @@ def test_create_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.create_product] = mock_rpc request = {} @@ -9692,64 +8726,59 @@ def test_create_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_product_rest_required_fields( - request_type=product_search_service.CreateProductRequest, -): +def test_create_product_rest_required_fields(request_type=product_search_service.CreateProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("product_id",)) + assert not set(unset_fields) - set(("product_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9759,32 +8788,24 @@ def test_create_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_product._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("productId",)) - & set( - ( - "parent", - "product", - ) - ) - ) + assert set(unset_fields) == (set(("productId", )) & set(("parent", "product", ))) def test_create_product_rest_flattened(): @@ -9794,18 +8815,18 @@ def test_create_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) mock_args.update(sample_request) @@ -9815,7 +8836,7 @@ def test_create_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -9825,14 +8846,10 @@ def test_create_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*}/products" % client.transport._host, args[1]) -def test_create_product_rest_flattened_error(transport: str = "rest"): +def test_create_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9843,9 +8860,9 @@ def test_create_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_product( product_search_service.CreateProductRequest(), - parent="parent_value", - product=product_search_service.Product(name="name_value"), - product_id="product_id_value", + parent='parent_value', + product=product_search_service.Product(name='name_value'), + product_id='product_id_value', ) @@ -9867,9 +8884,7 @@ def test_list_products_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} @@ -9885,67 +8900,57 @@ def test_list_products_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_products_rest_required_fields( - request_type=product_search_service.ListProductsRequest, -): +def test_list_products_rest_required_fields(request_type=product_search_service.ListProductsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -9956,32 +8961,24 @@ def test_list_products_rest_required_fields( return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_products_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_products._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_products_rest_flattened(): @@ -9991,16 +8988,16 @@ def test_list_products_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -10010,7 +9007,7 @@ def test_list_products_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10020,14 +9017,10 @@ def test_list_products_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*}/products" % client.transport._host, args[1]) -def test_list_products_rest_flattened_error(transport: str = "rest"): +def test_list_products_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10038,20 +9031,20 @@ def test_list_products_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_products( product_search_service.ListProductsRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_products_rest_pager(transport: str = "rest"): +def test_list_products_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductsResponse( @@ -10060,17 +9053,17 @@ def test_list_products_rest_pager(transport: str = "rest"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsResponse( products=[ @@ -10083,25 +9076,24 @@ def test_list_products_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductsResponse.to_json(x) for x in response - ) + response = tuple(product_search_service.ListProductsResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} pager = client.list_products(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) + assert all(isinstance(i, product_search_service.Product) + for i in results) pages = list(client.list_products(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -10123,9 +9115,7 @@ def test_get_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.get_product] = mock_rpc request = {} @@ -10141,60 +9131,55 @@ def test_get_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_product_rest_required_fields( - request_type=product_search_service.GetProductRequest, -): +def test_get_product_rest_required_fields(request_type=product_search_service.GetProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -10205,24 +9190,24 @@ def test_get_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_product_rest_flattened(): @@ -10232,16 +9217,16 @@ def test_get_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/products/sample3"} + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -10251,7 +9236,7 @@ def test_get_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10261,14 +9246,10 @@ def test_get_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_get_product_rest_flattened_error(transport: str = "rest"): +def test_get_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10279,7 +9260,7 @@ def test_get_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_product( product_search_service.GetProductRequest(), - name="name_value", + name='name_value', ) @@ -10301,9 +9282,7 @@ def test_update_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} @@ -10319,59 +9298,54 @@ def test_update_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_product_rest_required_fields( - request_type=product_search_service.UpdateProductRequest, -): +def test_update_product_rest_required_fields(request_type=product_search_service.UpdateProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("update_mask", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10381,24 +9355,24 @@ def test_update_product_rest_required_fields( return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_update_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.update_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("product",))) + assert set(unset_fields) == (set(("updateMask", )) & set(("product", ))) def test_update_product_rest_flattened(): @@ -10408,19 +9382,17 @@ def test_update_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product() # get arguments that satisfy an http rule for this method - sample_request = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } + sample_request = {'product': {'name': 'projects/sample1/locations/sample2/products/sample3'}} # get truthy value for each flattened field mock_args = dict( - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) mock_args.update(sample_request) @@ -10430,7 +9402,7 @@ def test_update_product_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10440,14 +9412,10 @@ def test_update_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{product.name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{product.name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_update_product_rest_flattened_error(transport: str = "rest"): +def test_update_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10458,8 +9426,8 @@ def test_update_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.update_product( product_search_service.UpdateProductRequest(), - product=product_search_service.Product(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + product=product_search_service.Product(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), ) @@ -10481,9 +9449,7 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc request = {} @@ -10499,85 +9465,80 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_product_rest_required_fields( - request_type=product_search_service.DeleteProductRequest, -): +def test_delete_product_rest_required_fields(request_type=product_search_service.DeleteProductRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_product._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_product_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_product_rest_flattened(): @@ -10587,24 +9548,24 @@ def test_delete_product_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/products/sample3"} + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10614,14 +9575,10 @@ def test_delete_product_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/products/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/products/*}" % client.transport._host, args[1]) -def test_delete_product_rest_flattened_error(transport: str = "rest"): +def test_delete_product_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10632,7 +9589,7 @@ def test_delete_product_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_product( product_search_service.DeleteProductRequest(), - name="name_value", + name='name_value', ) @@ -10650,19 +9607,12 @@ def test_create_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.create_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_reference_image] = mock_rpc request = {} client.create_reference_image(request) @@ -10677,64 +9627,59 @@ def test_create_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_reference_image_rest_required_fields( - request_type=product_search_service.CreateReferenceImageRequest, -): +def test_create_reference_image_rest_required_fields(request_type=product_search_service.CreateReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reference_image._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_reference_image._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("reference_image_id",)) + assert not set(unset_fields) - set(("reference_image_id", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10744,32 +9689,24 @@ def test_create_reference_image_rest_required_fields( return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_create_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.create_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("referenceImageId",)) - & set( - ( - "parent", - "referenceImage", - ) - ) - ) + assert set(unset_fields) == (set(("referenceImageId", )) & set(("parent", "referenceImage", ))) def test_create_reference_image_rest_flattened(): @@ -10779,20 +9716,18 @@ def test_create_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) mock_args.update(sample_request) @@ -10802,7 +9737,7 @@ def test_create_reference_image_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10812,14 +9747,10 @@ def test_create_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages" % client.transport._host, args[1]) -def test_create_reference_image_rest_flattened_error(transport: str = "rest"): +def test_create_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10830,9 +9761,9 @@ def test_create_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.create_reference_image( product_search_service.CreateReferenceImageRequest(), - parent="parent_value", - reference_image=product_search_service.ReferenceImage(name="name_value"), - reference_image_id="reference_image_id_value", + parent='parent_value', + reference_image=product_search_service.ReferenceImage(name='name_value'), + reference_image_id='reference_image_id_value', ) @@ -10850,19 +9781,12 @@ def test_delete_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_reference_image - in client._transport._wrapped_methods - ) + assert client._transport.delete_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_reference_image] = mock_rpc request = {} client.delete_reference_image(request) @@ -10877,85 +9801,80 @@ def test_delete_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_reference_image_rest_required_fields( - request_type=product_search_service.DeleteReferenceImageRequest, -): +def test_delete_reference_image_rest_required_fields(request_type=product_search_service.DeleteReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_delete_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.delete_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_delete_reference_image_rest_flattened(): @@ -10965,26 +9884,24 @@ def test_delete_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/sample4'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -10994,14 +9911,10 @@ def test_delete_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" % client.transport._host, args[1]) -def test_delete_reference_image_rest_flattened_error(transport: str = "rest"): +def test_delete_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11012,7 +9925,7 @@ def test_delete_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.delete_reference_image( product_search_service.DeleteReferenceImageRequest(), - name="name_value", + name='name_value', ) @@ -11030,19 +9943,12 @@ def test_list_reference_images_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_reference_images - in client._transport._wrapped_methods - ) + assert client._transport.list_reference_images in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reference_images - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_reference_images] = mock_rpc request = {} client.list_reference_images(request) @@ -11057,67 +9963,57 @@ def test_list_reference_images_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_reference_images_rest_required_fields( - request_type=product_search_service.ListReferenceImagesRequest, -): +def test_list_reference_images_rest_required_fields(request_type=product_search_service.ListReferenceImagesRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reference_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reference_images._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reference_images._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_reference_images._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("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" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11125,37 +10021,27 @@ def test_list_reference_images_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_reference_images(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_reference_images_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_reference_images._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) def test_list_reference_images_rest_flattened(): @@ -11165,18 +10051,16 @@ def test_list_reference_images_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -11184,11 +10068,9 @@ def test_list_reference_images_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11198,14 +10080,10 @@ def test_list_reference_images_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages" % client.transport._host, args[1]) -def test_list_reference_images_rest_flattened_error(transport: str = "rest"): +def test_list_reference_images_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11216,20 +10094,20 @@ def test_list_reference_images_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.list_reference_images( product_search_service.ListReferenceImagesRequest(), - parent="parent_value", + parent='parent_value', ) -def test_list_reference_images_rest_pager(transport: str = "rest"): +def test_list_reference_images_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListReferenceImagesResponse( @@ -11238,17 +10116,17 @@ def test_list_reference_images_rest_pager(transport: str = "rest"): product_search_service.ReferenceImage(), product_search_service.ReferenceImage(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListReferenceImagesResponse( reference_images=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListReferenceImagesResponse( reference_images=[ product_search_service.ReferenceImage(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListReferenceImagesResponse( reference_images=[ @@ -11261,30 +10139,24 @@ def test_list_reference_images_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListReferenceImagesResponse.to_json(x) - for x in response - ) + response = tuple(product_search_service.ListReferenceImagesResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/products/sample3" - } + sample_request = {'parent': 'projects/sample1/locations/sample2/products/sample3'} pager = client.list_reference_images(request=sample_request) results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, product_search_service.ReferenceImage) for i in results - ) + assert all(isinstance(i, product_search_service.ReferenceImage) + for i in results) pages = list(client.list_reference_images(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -11302,18 +10174,12 @@ def test_get_reference_image_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_reference_image in client._transport._wrapped_methods - ) + assert client._transport.get_reference_image in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reference_image - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_reference_image] = mock_rpc request = {} client.get_reference_image(request) @@ -11328,60 +10194,55 @@ def test_get_reference_image_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_reference_image_rest_required_fields( - request_type=product_search_service.GetReferenceImageRequest, -): +def test_get_reference_image_rest_required_fields(request_type=product_search_service.GetReferenceImageRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reference_image._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_reference_image._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11392,24 +10253,24 @@ def test_get_reference_image_rest_required_fields( return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_reference_image(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_get_reference_image_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.get_reference_image._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(()) & set(("name", ))) def test_get_reference_image_rest_flattened(): @@ -11419,18 +10280,16 @@ def test_get_reference_image_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + sample_request = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/sample4'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -11440,7 +10299,7 @@ def test_get_reference_image_rest_flattened(): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11450,14 +10309,10 @@ def test_get_reference_image_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" % client.transport._host, args[1]) -def test_get_reference_image_rest_flattened_error(transport: str = "rest"): +def test_get_reference_image_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11468,7 +10323,7 @@ def test_get_reference_image_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.get_reference_image( product_search_service.GetReferenceImageRequest(), - name="name_value", + name='name_value', ) @@ -11486,19 +10341,12 @@ def test_add_product_to_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.add_product_to_product_set - in client._transport._wrapped_methods - ) + assert client._transport.add_product_to_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_product_to_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_product_to_product_set] = mock_rpc request = {} client.add_product_to_product_set(request) @@ -11513,9 +10361,7 @@ def test_add_product_to_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_add_product_to_product_set_rest_required_fields( - request_type=product_search_service.AddProductToProductSetRequest, -): +def test_add_product_to_product_set_rest_required_fields(request_type=product_search_service.AddProductToProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} @@ -11523,88 +10369,77 @@ def test_add_product_to_product_set_rest_required_fields( request_init["product"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_product_to_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_product_to_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["product"] = "product_value" + jsonified_request["name"] = 'name_value' + jsonified_request["product"] = 'product_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_product_to_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_product_to_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" + assert jsonified_request["product"] == 'product_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_product_to_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_add_product_to_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.add_product_to_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "product", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "product", ))) def test_add_product_to_product_set_rest_flattened(): @@ -11614,27 +10449,25 @@ def test_add_product_to_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11644,14 +10477,10 @@ def test_add_product_to_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct" % client.transport._host, args[1]) -def test_add_product_to_product_set_rest_flattened_error(transport: str = "rest"): +def test_add_product_to_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11662,8 +10491,8 @@ def test_add_product_to_product_set_rest_flattened_error(transport: str = "rest" with pytest.raises(ValueError): client.add_product_to_product_set( product_search_service.AddProductToProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) @@ -11681,19 +10510,12 @@ def test_remove_product_from_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.remove_product_from_product_set - in client._transport._wrapped_methods - ) + assert client._transport.remove_product_from_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_product_from_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_product_from_product_set] = mock_rpc request = {} client.remove_product_from_product_set(request) @@ -11708,9 +10530,7 @@ def test_remove_product_from_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_remove_product_from_product_set_rest_required_fields( - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +def test_remove_product_from_product_set_rest_required_fields(request_type=product_search_service.RemoveProductFromProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} @@ -11718,90 +10538,77 @@ def test_remove_product_from_product_set_rest_required_fields( request_init["product"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_product_from_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_product_from_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["product"] = "product_value" + jsonified_request["name"] = 'name_value' + jsonified_request["product"] = 'product_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_product_from_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_product_from_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" + assert jsonified_request["product"] == 'product_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = '' - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_product_from_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_remove_product_from_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) - unset_fields = transport.remove_product_from_product_set._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "product", - ) - ) - ) + unset_fields = transport.remove_product_from_product_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "product", ))) def test_remove_product_from_product_set_rest_flattened(): @@ -11811,27 +10618,25 @@ def test_remove_product_from_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -11841,14 +10646,10 @@ def test_remove_product_from_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" % client.transport._host, args[1]) -def test_remove_product_from_product_set_rest_flattened_error(transport: str = "rest"): +def test_remove_product_from_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11859,8 +10660,8 @@ def test_remove_product_from_product_set_rest_flattened_error(transport: str = " with pytest.raises(ValueError): client.remove_product_from_product_set( product_search_service.RemoveProductFromProductSetRequest(), - name="name_value", - product="product_value", + name='name_value', + product='product_value', ) @@ -11878,19 +10679,12 @@ def test_list_products_in_product_set_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_products_in_product_set - in client._transport._wrapped_methods - ) + assert client._transport.list_products_in_product_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_products_in_product_set - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_products_in_product_set] = mock_rpc request = {} client.list_products_in_product_set(request) @@ -11905,67 +10699,57 @@ def test_list_products_in_product_set_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_products_in_product_set_rest_required_fields( - request_type=product_search_service.ListProductsInProductSetRequest, -): +def test_list_products_in_product_set_rest_required_fields(request_type=product_search_service.ListProductsInProductSetRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products_in_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products_in_product_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["name"] = 'name_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_products_in_product_set._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_products_in_product_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("page_size", "page_token", )) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, } transcode.return_value = transcode_result @@ -11973,37 +10757,27 @@ def test_list_products_in_product_set_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products_in_product_set(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_list_products_in_product_set_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.list_products_in_product_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("name",)) - ) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) def test_list_products_in_product_set_rest_flattened(): @@ -12013,18 +10787,16 @@ def test_list_products_in_product_set_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} # get truthy value for each flattened field mock_args = dict( - name="name_value", + name='name_value', ) mock_args.update(sample_request) @@ -12032,11 +10804,9 @@ def test_list_products_in_product_set_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -12046,14 +10816,10 @@ def test_list_products_in_product_set_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products" % client.transport._host, args[1]) -def test_list_products_in_product_set_rest_flattened_error(transport: str = "rest"): +def test_list_products_in_product_set_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12064,20 +10830,20 @@ def test_list_products_in_product_set_rest_flattened_error(transport: str = "res with pytest.raises(ValueError): client.list_products_in_product_set( product_search_service.ListProductsInProductSetRequest(), - name="name_value", + name='name_value', ) -def test_list_products_in_product_set_rest_pager(transport: str = "rest"): +def test_list_products_in_product_set_rest_pager(transport: str = 'rest'): client = ProductSearchClient( 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: + 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: + #with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( product_search_service.ListProductsInProductSetResponse( @@ -12086,17 +10852,17 @@ def test_list_products_in_product_set_rest_pager(transport: str = "rest"): product_search_service.Product(), product_search_service.Product(), ], - next_page_token="abc", + next_page_token='abc', ), product_search_service.ListProductsInProductSetResponse( products=[], - next_page_token="def", + next_page_token='def', ), product_search_service.ListProductsInProductSetResponse( products=[ product_search_service.Product(), ], - next_page_token="ghi", + next_page_token='ghi', ), product_search_service.ListProductsInProductSetResponse( products=[ @@ -12109,28 +10875,24 @@ def test_list_products_in_product_set_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple( - product_search_service.ListProductsInProductSetResponse.to_json(x) - for x in response - ) + response = tuple(product_search_service.ListProductsInProductSetResponse.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._content = response_val.encode('UTF-8') return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } + sample_request = {'name': 'projects/sample1/locations/sample2/productSets/sample3'} pager = client.list_products_in_product_set(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, product_search_service.Product) for i in results) + assert all(isinstance(i, product_search_service.Product) + for i in results) pages = list(client.list_products_in_product_set(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + for page_, token in zip(pages, ['abc','def','ghi', '']): assert page_.raw_page.next_page_token == token @@ -12148,18 +10910,12 @@ def test_import_product_sets_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.import_product_sets in client._transport._wrapped_methods - ) + assert client._transport.import_product_sets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_product_sets - ] = mock_rpc + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_product_sets] = mock_rpc request = {} client.import_product_sets(request) @@ -12178,94 +10934,81 @@ def test_import_product_sets_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_import_product_sets_rest_required_fields( - request_type=product_search_service.ImportProductSetsRequest, -): +def test_import_product_sets_rest_required_fields(request_type=product_search_service.ImportProductSetsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_product_sets._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_product_sets._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_product_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.import_product_sets(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_import_product_sets_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.import_product_sets._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("parent", "inputConfig", ))) def test_import_product_sets_rest_flattened(): @@ -12275,21 +11018,17 @@ def test_import_product_sets_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) mock_args.update(sample_request) @@ -12297,7 +11036,7 @@ def test_import_product_sets_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -12307,14 +11046,10 @@ def test_import_product_sets_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*}/productSets:import" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*}/productSets:import" % client.transport._host, args[1]) -def test_import_product_sets_rest_flattened_error(transport: str = "rest"): +def test_import_product_sets_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12325,12 +11060,8 @@ def test_import_product_sets_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.import_product_sets( product_search_service.ImportProductSetsRequest(), - parent="parent_value", - input_config=product_search_service.ImportProductSetsInputConfig( - gcs_source=product_search_service.ImportProductSetsGcsSource( - csv_file_uri="csv_file_uri_value" - ) - ), + parent='parent_value', + input_config=product_search_service.ImportProductSetsInputConfig(gcs_source=product_search_service.ImportProductSetsGcsSource(csv_file_uri='csv_file_uri_value')), ) @@ -12352,9 +11083,7 @@ def test_purge_products_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.purge_products] = mock_rpc request = {} @@ -12374,86 +11103,81 @@ def test_purge_products_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_purge_products_rest_required_fields( - request_type=product_search_service.PurgeProductsRequest, -): +def test_purge_products_rest_required_fields(request_type=product_search_service.PurgeProductsRequest): transport_class = transports.ProductSearchRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).purge_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_products._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" + jsonified_request["parent"] = 'parent_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).purge_products._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_products._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert jsonified_request["parent"] == 'parent_value' client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.Operation(name='operations/spam') # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + 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: + 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, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.purge_products(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_purge_products_rest_unset_required_fields(): - transport = transports.ProductSearchRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.ProductSearchRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.purge_products._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) + assert set(unset_fields) == (set(()) & set(("parent", ))) def test_purge_products_rest_flattened(): @@ -12463,16 +11187,16 @@ def test_purge_products_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {'parent': 'projects/sample1/locations/sample2'} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + parent='parent_value', ) mock_args.update(sample_request) @@ -12480,7 +11204,7 @@ def test_purge_products_rest_flattened(): 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") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -12490,14 +11214,10 @@ def test_purge_products_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1p4beta1/{parent=projects/*/locations/*}/products:purge" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1p4beta1/{parent=projects/*/locations/*}/products:purge" % client.transport._host, args[1]) -def test_purge_products_rest_flattened_error(transport: str = "rest"): +def test_purge_products_rest_flattened_error(transport: str = 'rest'): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12508,7 +11228,7 @@ def test_purge_products_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.purge_products( product_search_service.PurgeProductsRequest(), - parent="parent_value", + parent='parent_value', ) @@ -12550,7 +11270,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ProductSearchClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -12572,7 +11293,6 @@ def test_transport_instance(): client = ProductSearchClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( @@ -12587,23 +11307,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - transports.ProductSearchRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + transports.ProductSearchRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = ProductSearchClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -12613,7 +11328,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -12628,8 +11344,8 @@ def test_create_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.create_product_set(request=None) @@ -12651,8 +11367,8 @@ def test_list_product_sets_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: call.return_value = product_search_service.ListProductSetsResponse() client.list_product_sets(request=None) @@ -12673,7 +11389,9 @@ def test_get_product_set_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.get_product_set(request=None) @@ -12695,8 +11413,8 @@ def test_update_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: call.return_value = product_search_service.ProductSet() client.update_product_set(request=None) @@ -12718,8 +11436,8 @@ def test_delete_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: call.return_value = None client.delete_product_set(request=None) @@ -12740,7 +11458,9 @@ def test_create_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: call.return_value = product_search_service.Product() client.create_product(request=None) @@ -12761,7 +11481,9 @@ def test_list_products_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: call.return_value = product_search_service.ListProductsResponse() client.list_products(request=None) @@ -12782,7 +11504,9 @@ def test_get_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: call.return_value = product_search_service.Product() client.get_product(request=None) @@ -12803,7 +11527,9 @@ def test_update_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: call.return_value = product_search_service.Product() client.update_product(request=None) @@ -12824,7 +11550,9 @@ def test_delete_product_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: call.return_value = None client.delete_product(request=None) @@ -12846,8 +11574,8 @@ def test_create_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.create_reference_image(request=None) @@ -12869,8 +11597,8 @@ def test_delete_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: call.return_value = None client.delete_reference_image(request=None) @@ -12892,8 +11620,8 @@ def test_list_reference_images_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: call.return_value = product_search_service.ListReferenceImagesResponse() client.list_reference_images(request=None) @@ -12915,8 +11643,8 @@ def test_get_reference_image_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: call.return_value = product_search_service.ReferenceImage() client.get_reference_image(request=None) @@ -12938,8 +11666,8 @@ def test_add_product_to_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: call.return_value = None client.add_product_to_product_set(request=None) @@ -12961,8 +11689,8 @@ def test_remove_product_from_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: call.return_value = None client.remove_product_from_product_set(request=None) @@ -12984,8 +11712,8 @@ def test_list_products_in_product_set_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: call.return_value = product_search_service.ListProductsInProductSetResponse() client.list_products_in_product_set(request=None) @@ -13007,9 +11735,9 @@ def test_import_product_sets_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") + type(client.transport.import_product_sets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.import_product_sets(request=None) # Establish that the underlying stub method was called. @@ -13029,8 +11757,10 @@ def test_purge_products_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') client.purge_products(request=None) # Establish that the underlying stub method was called. @@ -13050,7 +11780,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -13066,15 +11797,13 @@ async def test_create_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.create_product_set(request=None) # Establish that the underlying stub method was called. @@ -13096,14 +11825,12 @@ async def test_list_product_sets_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductSetsResponse( + next_page_token='next_page_token_value', + )) await client.list_product_sets(request=None) # Establish that the underlying stub method was called. @@ -13124,14 +11851,14 @@ async def test_get_product_set_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.get_product_set(request=None) # Establish that the underlying stub method was called. @@ -13153,15 +11880,13 @@ async def test_update_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ProductSet( + name='name_value', + display_name='display_name_value', + )) await client.update_product_set(request=None) # Establish that the underlying stub method was called. @@ -13183,8 +11908,8 @@ async def test_delete_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product_set(request=None) @@ -13207,16 +11932,16 @@ async def test_create_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.create_product(request=None) # Establish that the underlying stub method was called. @@ -13237,13 +11962,13 @@ async def test_list_products_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsResponse( + next_page_token='next_page_token_value', + )) await client.list_products(request=None) # Establish that the underlying stub method was called. @@ -13264,16 +11989,16 @@ async def test_get_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.get_product(request=None) # Establish that the underlying stub method was called. @@ -13294,16 +12019,16 @@ async def test_update_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.Product( + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', + )) await client.update_product(request=None) # Establish that the underlying stub method was called. @@ -13324,7 +12049,9 @@ async def test_delete_product_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_product(request=None) @@ -13348,15 +12075,13 @@ async def test_create_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) await client.create_reference_image(request=None) # Establish that the underlying stub method was called. @@ -13378,8 +12103,8 @@ async def test_delete_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_reference_image(request=None) @@ -13403,15 +12128,13 @@ async def test_list_reference_images_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListReferenceImagesResponse( + page_size=951, + next_page_token='next_page_token_value', + )) await client.list_reference_images(request=None) # Establish that the underlying stub method was called. @@ -13433,15 +12156,13 @@ async def test_get_reference_image_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ReferenceImage( + name='name_value', + uri='uri_value', + )) await client.get_reference_image(request=None) # Establish that the underlying stub method was called. @@ -13463,8 +12184,8 @@ async def test_add_product_to_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.add_product_to_product_set(request=None) @@ -13488,8 +12209,8 @@ async def test_remove_product_from_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.remove_product_from_product_set(request=None) @@ -13513,14 +12234,12 @@ async def test_list_products_in_product_set_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(product_search_service.ListProductsInProductSetResponse( + next_page_token='next_page_token_value', + )) await client.list_products_in_product_set(request=None) # Establish that the underlying stub method was called. @@ -13542,11 +12261,11 @@ async def test_import_product_sets_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.import_product_sets(request=None) @@ -13568,10 +12287,12 @@ async def test_purge_products_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name='operations/spam') ) await client.purge_products(request=None) @@ -13590,23 +12311,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_create_product_set_rest_bad_request( - request_type=product_search_service.CreateProductSetRequest, -): +def test_create_product_set_rest_bad_request(request_type=product_search_service.CreateProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13615,43 +12333,25 @@ def test_create_product_set_rest_bad_request( client.create_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductSetRequest, + dict, +]) def test_create_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["product_set"] = { - "name": "name_value", - "display_name": "display_name_value", - "index_time": {"seconds": 751, "nanos": 543}, - "index_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["product_set"] = {'name': 'name_value', 'display_name': 'display_name_value', 'index_time': {'seconds': 751, 'nanos': 543}, 'index_error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.CreateProductSetRequest.meta.fields[ - "product_set" - ] + test_field = product_search_service.CreateProductSetRequest.meta.fields["product_set"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13665,7 +12365,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -13679,7 +12379,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product_set"].items(): # pragma: NO COVER + for field, value in request_init["product_set"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13694,16 +12394,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -13716,11 +12412,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13730,44 +12426,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_create_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateProductSetRequest.pb( - product_search_service.CreateProductSetRequest() - ) + pb_message = product_search_service.CreateProductSetRequest.pb(product_search_service.CreateProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13778,13 +12464,11 @@ def test_create_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.CreateProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -13792,36 +12476,27 @@ def test_create_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.create_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_product_sets_rest_bad_request( - request_type=product_search_service.ListProductSetsRequest, -): +def test_list_product_sets_rest_bad_request(request_type=product_search_service.ListProductSetsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13830,27 +12505,25 @@ def test_list_product_sets_rest_bad_request( client.list_product_sets(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductSetsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductSetsRequest, + dict, +]) def test_list_product_sets_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductSetsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -13860,43 +12533,33 @@ def test_list_product_sets_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ListProductSetsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_product_sets(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_product_sets_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_product_sets" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_list_product_sets_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_product_sets" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_product_sets") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_product_sets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_product_sets") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductSetsRequest.pb( - product_search_service.ListProductSetsRequest() - ) + pb_message = product_search_service.ListProductSetsRequest.pb(product_search_service.ListProductSetsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13907,53 +12570,39 @@ def test_list_product_sets_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductSetsResponse.to_json( - product_search_service.ListProductSetsResponse() - ) + return_value = product_search_service.ListProductSetsResponse.to_json(product_search_service.ListProductSetsResponse()) req.return_value.content = return_value request = product_search_service.ListProductSetsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductSetsResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductSetsResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductSetsResponse(), metadata - client.list_product_sets( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_product_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_product_set_rest_bad_request( - request_type=product_search_service.GetProductSetRequest, -): +def test_get_product_set_rest_bad_request(request_type=product_search_service.GetProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -13962,28 +12611,26 @@ def test_get_product_set_rest_bad_request( client.get_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductSetRequest, + dict, +]) def test_get_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -13993,44 +12640,34 @@ def test_get_product_set_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_get_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetProductSetRequest.pb( - product_search_service.GetProductSetRequest() - ) + pb_message = product_search_service.GetProductSetRequest.pb(product_search_service.GetProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14041,13 +12678,11 @@ def test_get_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.GetProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14055,40 +12690,27 @@ def test_get_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.get_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_product_set_rest_bad_request( - request_type=product_search_service.UpdateProductSetRequest, -): +def test_update_product_set_rest_bad_request(request_type=product_search_service.UpdateProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } + request_init = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14097,47 +12719,25 @@ def test_update_product_set_rest_bad_request( client.update_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductSetRequest, + dict, +]) def test_update_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product_set": { - "name": "projects/sample1/locations/sample2/productSets/sample3" - } - } - request_init["product_set"] = { - "name": "projects/sample1/locations/sample2/productSets/sample3", - "display_name": "display_name_value", - "index_time": {"seconds": 751, "nanos": 543}, - "index_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - } + request_init = {'product_set': {'name': 'projects/sample1/locations/sample2/productSets/sample3'}} + request_init["product_set"] = {'name': 'projects/sample1/locations/sample2/productSets/sample3', 'display_name': 'display_name_value', 'index_time': {'seconds': 751, 'nanos': 543}, 'index_error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.UpdateProductSetRequest.meta.fields[ - "product_set" - ] + test_field = product_search_service.UpdateProductSetRequest.meta.fields["product_set"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -14151,7 +12751,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14165,7 +12765,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product_set"].items(): # pragma: NO COVER + for field, value in request_init["product_set"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14180,16 +12780,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14202,11 +12798,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ProductSet( - name="name_value", - display_name="display_name_value", + name='name_value', + display_name='display_name_value', ) # Wrap the value into a proper Response obj @@ -14216,44 +12812,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ProductSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ProductSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_update_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_update_product_set_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_update_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_update_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.UpdateProductSetRequest.pb( - product_search_service.UpdateProductSetRequest() - ) + pb_message = product_search_service.UpdateProductSetRequest.pb(product_search_service.UpdateProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14264,13 +12850,11 @@ def test_update_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ProductSet.to_json( - product_search_service.ProductSet() - ) + return_value = product_search_service.ProductSet.to_json(product_search_service.ProductSet()) req.return_value.content = return_value request = product_search_service.UpdateProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14278,36 +12862,27 @@ def test_update_product_set_rest_interceptors(null_interceptor): post.return_value = product_search_service.ProductSet() post_with_metadata.return_value = product_search_service.ProductSet(), metadata - client.update_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_product_set_rest_bad_request( - request_type=product_search_service.DeleteProductSetRequest, -): +def test_delete_product_set_rest_bad_request(request_type=product_search_service.DeleteProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14316,32 +12891,30 @@ def test_delete_product_set_rest_bad_request( client.delete_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductSetRequest, + dict, +]) def test_delete_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product_set(request) @@ -14354,23 +12927,15 @@ def test_delete_product_set_rest_call_success(request_type): def test_delete_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteProductSetRequest.pb( - product_search_service.DeleteProductSetRequest() - ) + pb_message = product_search_service.DeleteProductSetRequest.pb(product_search_service.DeleteProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14383,40 +12948,31 @@ def test_delete_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_create_product_rest_bad_request( - request_type=product_search_service.CreateProductRequest, -): +def test_create_product_rest_bad_request(request_type=product_search_service.CreateProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14425,27 +12981,19 @@ def test_create_product_rest_bad_request( client.create_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateProductRequest, + dict, +]) def test_create_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["product"] = { - "name": "name_value", - "display_name": "display_name_value", - "description": "description_value", - "product_category": "product_category_value", - "product_labels": [{"key": "key_value", "value": "value_value"}], - } + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["product"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'product_category': 'product_category_value', 'product_labels': [{'key': 'key_value', 'value': 'value_value'}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -14465,7 +13013,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14479,7 +13027,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER + for field, value in request_init["product"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14494,16 +13042,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14516,13 +13060,13 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -14532,46 +13076,36 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_create_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateProductRequest.pb( - product_search_service.CreateProductRequest() - ) + pb_message = product_search_service.CreateProductRequest.pb(product_search_service.CreateProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14582,13 +13116,11 @@ def test_create_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.CreateProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14596,36 +13128,27 @@ def test_create_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.create_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_products_rest_bad_request( - request_type=product_search_service.ListProductsRequest, -): +def test_list_products_rest_bad_request(request_type=product_search_service.ListProductsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14634,27 +13157,25 @@ def test_list_products_rest_bad_request( client.list_products(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsRequest, + dict, +]) def test_list_products_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -14664,43 +13185,33 @@ def test_list_products_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_products_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_products" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_list_products_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_products" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_products") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductsRequest.pb( - product_search_service.ListProductsRequest() - ) + pb_message = product_search_service.ListProductsRequest.pb(product_search_service.ListProductsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14711,53 +13222,39 @@ def test_list_products_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductsResponse.to_json( - product_search_service.ListProductsResponse() - ) + return_value = product_search_service.ListProductsResponse.to_json(product_search_service.ListProductsResponse()) req.return_value.content = return_value request = product_search_service.ListProductsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductsResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductsResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductsResponse(), metadata - client.list_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_product_rest_bad_request( - request_type=product_search_service.GetProductRequest, -): +def test_get_product_rest_bad_request(request_type=product_search_service.GetProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14766,30 +13263,28 @@ def test_get_product_rest_bad_request( client.get_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetProductRequest, + dict, +]) def test_get_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -14799,46 +13294,36 @@ def test_get_product_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_get_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetProductRequest.pb( - product_search_service.GetProductRequest() - ) + pb_message = product_search_service.GetProductRequest.pb(product_search_service.GetProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14849,13 +13334,11 @@ def test_get_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.GetProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -14863,38 +13346,27 @@ def test_get_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.get_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_product_rest_bad_request( - request_type=product_search_service.UpdateProductRequest, -): +def test_update_product_rest_bad_request(request_type=product_search_service.UpdateProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } + request_init = {'product': {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -14903,29 +13375,19 @@ def test_update_product_rest_bad_request( client.update_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.UpdateProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.UpdateProductRequest, + dict, +]) def test_update_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "product": {"name": "projects/sample1/locations/sample2/products/sample3"} - } - request_init["product"] = { - "name": "projects/sample1/locations/sample2/products/sample3", - "display_name": "display_name_value", - "description": "description_value", - "product_category": "product_category_value", - "product_labels": [{"key": "key_value", "value": "value_value"}], - } + request_init = {'product': {'name': 'projects/sample1/locations/sample2/products/sample3'}} + request_init["product"] = {'name': 'projects/sample1/locations/sample2/products/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'product_category': 'product_category_value', 'product_labels': [{'key': 'key_value', 'value': 'value_value'}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -14945,7 +13407,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -14959,7 +13421,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER + for field, value in request_init["product"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14974,16 +13436,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -14996,13 +13454,13 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.Product( - name="name_value", - display_name="display_name_value", - description="description_value", - product_category="product_category_value", + name='name_value', + display_name='display_name_value', + description='description_value', + product_category='product_category_value', ) # Wrap the value into a proper Response obj @@ -15012,46 +13470,36 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_product(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.Product) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.product_category == "product_category_value" + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.product_category == 'product_category_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_update_product" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_update_product_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_update_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_update_product_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_update_product") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.UpdateProductRequest.pb( - product_search_service.UpdateProductRequest() - ) + pb_message = product_search_service.UpdateProductRequest.pb(product_search_service.UpdateProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15062,13 +13510,11 @@ def test_update_product_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.Product.to_json( - product_search_service.Product() - ) + return_value = product_search_service.Product.to_json(product_search_service.Product()) req.return_value.content = return_value request = product_search_service.UpdateProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -15076,36 +13522,27 @@ def test_update_product_rest_interceptors(null_interceptor): post.return_value = product_search_service.Product() post_with_metadata.return_value = product_search_service.Product(), metadata - client.update_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_product_rest_bad_request( - request_type=product_search_service.DeleteProductRequest, -): +def test_delete_product_rest_bad_request(request_type=product_search_service.DeleteProductRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15114,32 +13551,30 @@ def test_delete_product_rest_bad_request( client.delete_product(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteProductRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteProductRequest, + dict, +]) def test_delete_product_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_product(request) @@ -15152,23 +13587,15 @@ def test_delete_product_rest_call_success(request_type): def test_delete_product_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_product" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_product") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteProductRequest.pb( - product_search_service.DeleteProductRequest() - ) + pb_message = product_search_service.DeleteProductRequest.pb(product_search_service.DeleteProductRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15181,80 +13608,58 @@ def test_delete_product_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteProductRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_product(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_create_reference_image_rest_bad_request( - request_type=product_search_service.CreateReferenceImageRequest, -): +def test_create_reference_image_rest_bad_request(request_type=product_search_service.CreateReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_reference_image(request) - - -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.CreateReferenceImageRequest, - dict, - ], -) + client.create_reference_image(request) + + +@pytest.mark.parametrize("request_type", [ + product_search_service.CreateReferenceImageRequest, + dict, +]) def test_create_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} - request_init["reference_image"] = { - "name": "name_value", - "uri": "uri_value", - "bounding_polys": [ - { - "vertices": [{"x": 120, "y": 121}], - "normalized_vertices": [{"x": 0.12, "y": 0.121}], - } - ], - } + request_init = {'parent': 'projects/sample1/locations/sample2/products/sample3'} + request_init["reference_image"] = {'name': 'name_value', 'uri': 'uri_value', 'bounding_polys': [{'vertices': [{'x': 120, 'y': 121}], 'normalized_vertices': [{'x': 0.12, 'y': 0.121}]}]} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = product_search_service.CreateReferenceImageRequest.meta.fields[ - "reference_image" - ] + test_field = product_search_service.CreateReferenceImageRequest.meta.fields["reference_image"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -15268,7 +13673,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -15282,7 +13687,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["reference_image"].items(): # pragma: NO COVER + for field, value in request_init["reference_image"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -15297,16 +13702,12 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } + {"field": field, "subfield": subfield, "is_repeated": is_repeated} ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -15319,11 +13720,11 @@ def get_message_fields(field): 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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) # Wrap the value into a proper Response obj @@ -15333,45 +13734,34 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_reference_image(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_create_reference_image" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_create_reference_image_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_create_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_reference_image") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_create_reference_image_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_create_reference_image") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.CreateReferenceImageRequest.pb( - product_search_service.CreateReferenceImageRequest() - ) + pb_message = product_search_service.CreateReferenceImageRequest.pb(product_search_service.CreateReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15382,55 +13772,39 @@ def test_create_reference_image_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ReferenceImage.to_json( - product_search_service.ReferenceImage() - ) + return_value = product_search_service.ReferenceImage.to_json(product_search_service.ReferenceImage()) req.return_value.content = return_value request = product_search_service.CreateReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ReferenceImage() - post_with_metadata.return_value = ( - product_search_service.ReferenceImage(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ReferenceImage(), metadata - client.create_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.create_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_reference_image_rest_bad_request( - request_type=product_search_service.DeleteReferenceImageRequest, -): +def test_delete_reference_image_rest_bad_request(request_type=product_search_service.DeleteReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15439,34 +13813,30 @@ def test_delete_reference_image_rest_bad_request( client.delete_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.DeleteReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.DeleteReferenceImageRequest, + dict, +]) def test_delete_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_reference_image(request) @@ -15479,23 +13849,15 @@ def test_delete_reference_image_rest_call_success(request_type): def test_delete_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_delete_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_delete_reference_image") as pre: pre.assert_not_called() - pb_message = product_search_service.DeleteReferenceImageRequest.pb( - product_search_service.DeleteReferenceImageRequest() - ) + pb_message = product_search_service.DeleteReferenceImageRequest.pb(product_search_service.DeleteReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15508,40 +13870,31 @@ def test_delete_reference_image_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.DeleteReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.delete_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_list_reference_images_rest_bad_request( - request_type=product_search_service.ListReferenceImagesRequest, -): +def test_list_reference_images_rest_bad_request(request_type=product_search_service.ListReferenceImagesRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15550,28 +13903,26 @@ def test_list_reference_images_rest_bad_request( client.list_reference_images(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListReferenceImagesRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListReferenceImagesRequest, + dict, +]) def test_list_reference_images_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/products/sample3"} + request_init = {'parent': 'projects/sample1/locations/sample2/products/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListReferenceImagesResponse( - page_size=951, - next_page_token="next_page_token_value", + page_size=951, + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -15579,11 +13930,9 @@ def test_list_reference_images_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListReferenceImagesResponse.pb( - return_value - ) + return_value = product_search_service.ListReferenceImagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_reference_images(request) @@ -15591,37 +13940,26 @@ def test_list_reference_images_rest_call_success(request_type): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListReferenceImagesPager) assert response.page_size == 951 - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_reference_images_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_reference_images" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_list_reference_images_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_reference_images" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_reference_images") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_reference_images_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_reference_images") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListReferenceImagesRequest.pb( - product_search_service.ListReferenceImagesRequest() - ) + pb_message = product_search_service.ListReferenceImagesRequest.pb(product_search_service.ListReferenceImagesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15632,55 +13970,39 @@ def test_list_reference_images_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListReferenceImagesResponse.to_json( - product_search_service.ListReferenceImagesResponse() - ) + return_value = product_search_service.ListReferenceImagesResponse.to_json(product_search_service.ListReferenceImagesResponse()) req.return_value.content = return_value request = product_search_service.ListReferenceImagesRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListReferenceImagesResponse() - post_with_metadata.return_value = ( - product_search_service.ListReferenceImagesResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListReferenceImagesResponse(), metadata - client.list_reference_images( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_reference_images(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_reference_image_rest_bad_request( - request_type=product_search_service.GetReferenceImageRequest, -): +def test_get_reference_image_rest_bad_request(request_type=product_search_service.GetReferenceImageRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15689,30 +14011,26 @@ def test_get_reference_image_rest_bad_request( client.get_reference_image(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.GetReferenceImageRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.GetReferenceImageRequest, + dict, +]) def test_get_reference_image_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/products/sample3/referenceImages/sample4" - } + request_init = {'name': 'projects/sample1/locations/sample2/products/sample3/referenceImages/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ReferenceImage( - name="name_value", - uri="uri_value", + name='name_value', + uri='uri_value', ) # Wrap the value into a proper Response obj @@ -15722,45 +14040,34 @@ def test_get_reference_image_rest_call_success(request_type): # Convert return value to protobuf type return_value = product_search_service.ReferenceImage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_reference_image(request) # Establish that the response is the type that we expect. assert isinstance(response, product_search_service.ReferenceImage) - assert response.name == "name_value" - assert response.uri == "uri_value" + assert response.name == 'name_value' + assert response.uri == 'uri_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_reference_image_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_get_reference_image" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_get_reference_image_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_get_reference_image" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_reference_image") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_get_reference_image_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_get_reference_image") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.GetReferenceImageRequest.pb( - product_search_service.GetReferenceImageRequest() - ) + pb_message = product_search_service.GetReferenceImageRequest.pb(product_search_service.GetReferenceImageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15771,53 +14078,39 @@ def test_get_reference_image_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ReferenceImage.to_json( - product_search_service.ReferenceImage() - ) + return_value = product_search_service.ReferenceImage.to_json(product_search_service.ReferenceImage()) req.return_value.content = return_value request = product_search_service.GetReferenceImageRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ReferenceImage() - post_with_metadata.return_value = ( - product_search_service.ReferenceImage(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ReferenceImage(), metadata - client.get_reference_image( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_reference_image(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_add_product_to_product_set_rest_bad_request( - request_type=product_search_service.AddProductToProductSetRequest, -): +def test_add_product_to_product_set_rest_bad_request(request_type=product_search_service.AddProductToProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15826,32 +14119,30 @@ def test_add_product_to_product_set_rest_bad_request( client.add_product_to_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.AddProductToProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.AddProductToProductSetRequest, + dict, +]) def test_add_product_to_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_product_to_product_set(request) @@ -15864,23 +14155,15 @@ def test_add_product_to_product_set_rest_call_success(request_type): def test_add_product_to_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_add_product_to_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_add_product_to_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.AddProductToProductSetRequest.pb( - product_search_service.AddProductToProductSetRequest() - ) + pb_message = product_search_service.AddProductToProductSetRequest.pb(product_search_service.AddProductToProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15893,40 +14176,31 @@ def test_add_product_to_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.AddProductToProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.add_product_to_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.add_product_to_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_remove_product_from_product_set_rest_bad_request( - request_type=product_search_service.RemoveProductFromProductSetRequest, -): +def test_remove_product_from_product_set_rest_bad_request(request_type=product_search_service.RemoveProductFromProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -15935,32 +14209,30 @@ def test_remove_product_from_product_set_rest_bad_request( client.remove_product_from_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.RemoveProductFromProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.RemoveProductFromProductSetRequest, + dict, +]) def test_remove_product_from_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") + json_return_value = '' + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_product_from_product_set(request) @@ -15973,23 +14245,15 @@ def test_remove_product_from_product_set_rest_call_success(request_type): def test_remove_product_from_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "pre_remove_product_from_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_remove_product_from_product_set") as pre: pre.assert_not_called() - pb_message = product_search_service.RemoveProductFromProductSetRequest.pb( - product_search_service.RemoveProductFromProductSetRequest() - ) + pb_message = product_search_service.RemoveProductFromProductSetRequest.pb(product_search_service.RemoveProductFromProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16002,40 +14266,31 @@ def test_remove_product_from_product_set_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = product_search_service.RemoveProductFromProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.remove_product_from_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.remove_product_from_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() -def test_list_products_in_product_set_rest_bad_request( - request_type=product_search_service.ListProductsInProductSetRequest, -): +def test_list_products_in_product_set_rest_bad_request(request_type=product_search_service.ListProductsInProductSetRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -16044,27 +14299,25 @@ def test_list_products_in_product_set_rest_bad_request( client.list_products_in_product_set(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ListProductsInProductSetRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ListProductsInProductSetRequest, + dict, +]) def test_list_products_in_product_set_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/productSets/sample3"} + request_init = {'name': 'projects/sample1/locations/sample2/productSets/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: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = product_search_service.ListProductsInProductSetResponse( - next_page_token="next_page_token_value", + next_page_token='next_page_token_value', ) # Wrap the value into a proper Response obj @@ -16072,48 +14325,35 @@ def test_list_products_in_product_set_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_search_service.ListProductsInProductSetResponse.pb( - return_value - ) + return_value = product_search_service.ListProductsInProductSetResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_products_in_product_set(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetPager) - assert response.next_page_token == "next_page_token_value" + assert response.next_page_token == 'next_page_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_products_in_product_set_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_list_products_in_product_set" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_list_products_in_product_set_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_list_products_in_product_set" - ) as pre: + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_in_product_set") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_list_products_in_product_set_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_list_products_in_product_set") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ListProductsInProductSetRequest.pb( - product_search_service.ListProductsInProductSetRequest() - ) + pb_message = product_search_service.ListProductsInProductSetRequest.pb(product_search_service.ListProductsInProductSetRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16124,53 +14364,39 @@ def test_list_products_in_product_set_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = product_search_service.ListProductsInProductSetResponse.to_json( - product_search_service.ListProductsInProductSetResponse() - ) + return_value = product_search_service.ListProductsInProductSetResponse.to_json(product_search_service.ListProductsInProductSetResponse()) req.return_value.content = return_value request = product_search_service.ListProductsInProductSetRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = product_search_service.ListProductsInProductSetResponse() - post_with_metadata.return_value = ( - product_search_service.ListProductsInProductSetResponse(), - metadata, - ) + post_with_metadata.return_value = product_search_service.ListProductsInProductSetResponse(), metadata - client.list_products_in_product_set( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.list_products_in_product_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_import_product_sets_rest_bad_request( - request_type=product_search_service.ImportProductSetsRequest, -): +def test_import_product_sets_rest_bad_request(request_type=product_search_service.ImportProductSetsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -16179,32 +14405,30 @@ def test_import_product_sets_rest_bad_request( client.import_product_sets(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.ImportProductSetsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.ImportProductSetsRequest, + dict, +]) def test_import_product_sets_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.import_product_sets(request) @@ -16217,32 +14441,20 @@ def test_import_product_sets_rest_call_success(request_type): def test_import_product_sets_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_import_product_sets" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, - "post_import_product_sets_with_metadata", - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_import_product_sets" - ) as pre: + 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.ProductSearchRestInterceptor, "post_import_product_sets") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_import_product_sets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_import_product_sets") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.ImportProductSetsRequest.pb( - product_search_service.ImportProductSetsRequest() - ) + pb_message = product_search_service.ImportProductSetsRequest.pb(product_search_service.ImportProductSetsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16257,7 +14469,7 @@ def test_import_product_sets_rest_interceptors(null_interceptor): req.return_value.content = return_value request = product_search_service.ImportProductSetsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -16265,36 +14477,27 @@ def test_import_product_sets_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.import_product_sets( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.import_product_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_purge_products_rest_bad_request( - request_type=product_search_service.PurgeProductsRequest, -): +def test_purge_products_rest_bad_request(request_type=product_search_service.PurgeProductsRequest): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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 - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -16303,32 +14506,30 @@ def test_purge_products_rest_bad_request( client.purge_products(request) -@pytest.mark.parametrize( - "request_type", - [ - product_search_service.PurgeProductsRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + product_search_service.PurgeProductsRequest, + dict, +]) def test_purge_products_rest_call_success(request_type): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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: + 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") + return_value = operations_pb2.Operation(name='operations/spam') # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.purge_products(request) @@ -16341,31 +14542,20 @@ def test_purge_products_rest_call_success(request_type): def test_purge_products_rest_interceptors(null_interceptor): transport = transports.ProductSearchRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductSearchRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.ProductSearchRestInterceptor(), + ) client = ProductSearchClient(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.ProductSearchRestInterceptor, "post_purge_products" - ) as post, mock.patch.object( - transports.ProductSearchRestInterceptor, "post_purge_products_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.ProductSearchRestInterceptor, "pre_purge_products" - ) as pre: + 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.ProductSearchRestInterceptor, "post_purge_products") as post, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "post_purge_products_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProductSearchRestInterceptor, "pre_purge_products") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = product_search_service.PurgeProductsRequest.pb( - product_search_service.PurgeProductsRequest() - ) + pb_message = product_search_service.PurgeProductsRequest.pb(product_search_service.PurgeProductsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16380,7 +14570,7 @@ def test_purge_products_rest_interceptors(null_interceptor): req.return_value.content = return_value request = product_search_service.PurgeProductsRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -16388,22 +14578,16 @@ def test_purge_products_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.purge_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.purge_products(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -16418,8 +14602,8 @@ def test_create_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_product_set), "__call__" - ) as call: + type(client.transport.create_product_set), + '__call__') as call: client.create_product_set(request=None) # Establish that the underlying stub method was called. @@ -16440,8 +14624,8 @@ def test_list_product_sets_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_product_sets), "__call__" - ) as call: + type(client.transport.list_product_sets), + '__call__') as call: client.list_product_sets(request=None) # Establish that the underlying stub method was called. @@ -16461,7 +14645,9 @@ def test_get_product_set_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product_set), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product_set), + '__call__') as call: client.get_product_set(request=None) # Establish that the underlying stub method was called. @@ -16482,8 +14668,8 @@ def test_update_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_product_set), "__call__" - ) as call: + type(client.transport.update_product_set), + '__call__') as call: client.update_product_set(request=None) # Establish that the underlying stub method was called. @@ -16504,8 +14690,8 @@ def test_delete_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_product_set), "__call__" - ) as call: + type(client.transport.delete_product_set), + '__call__') as call: client.delete_product_set(request=None) # Establish that the underlying stub method was called. @@ -16525,7 +14711,9 @@ def test_create_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: + with mock.patch.object( + type(client.transport.create_product), + '__call__') as call: client.create_product(request=None) # Establish that the underlying stub method was called. @@ -16545,7 +14733,9 @@ def test_list_products_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: + with mock.patch.object( + type(client.transport.list_products), + '__call__') as call: client.list_products(request=None) # Establish that the underlying stub method was called. @@ -16565,7 +14755,9 @@ def test_get_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: + with mock.patch.object( + type(client.transport.get_product), + '__call__') as call: client.get_product(request=None) # Establish that the underlying stub method was called. @@ -16585,7 +14777,9 @@ def test_update_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: + with mock.patch.object( + type(client.transport.update_product), + '__call__') as call: client.update_product(request=None) # Establish that the underlying stub method was called. @@ -16605,7 +14799,9 @@ def test_delete_product_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_product), + '__call__') as call: client.delete_product(request=None) # Establish that the underlying stub method was called. @@ -16626,8 +14822,8 @@ def test_create_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_reference_image), "__call__" - ) as call: + type(client.transport.create_reference_image), + '__call__') as call: client.create_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16648,8 +14844,8 @@ def test_delete_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_reference_image), "__call__" - ) as call: + type(client.transport.delete_reference_image), + '__call__') as call: client.delete_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16670,8 +14866,8 @@ def test_list_reference_images_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reference_images), "__call__" - ) as call: + type(client.transport.list_reference_images), + '__call__') as call: client.list_reference_images(request=None) # Establish that the underlying stub method was called. @@ -16692,8 +14888,8 @@ def test_get_reference_image_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_reference_image), "__call__" - ) as call: + type(client.transport.get_reference_image), + '__call__') as call: client.get_reference_image(request=None) # Establish that the underlying stub method was called. @@ -16714,8 +14910,8 @@ def test_add_product_to_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_product_to_product_set), "__call__" - ) as call: + type(client.transport.add_product_to_product_set), + '__call__') as call: client.add_product_to_product_set(request=None) # Establish that the underlying stub method was called. @@ -16736,8 +14932,8 @@ def test_remove_product_from_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_product_from_product_set), "__call__" - ) as call: + type(client.transport.remove_product_from_product_set), + '__call__') as call: client.remove_product_from_product_set(request=None) # Establish that the underlying stub method was called. @@ -16758,8 +14954,8 @@ def test_list_products_in_product_set_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_products_in_product_set), "__call__" - ) as call: + type(client.transport.list_products_in_product_set), + '__call__') as call: client.list_products_in_product_set(request=None) # Establish that the underlying stub method was called. @@ -16780,8 +14976,8 @@ def test_import_product_sets_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.import_product_sets), "__call__" - ) as call: + type(client.transport.import_product_sets), + '__call__') as call: client.import_product_sets(request=None) # Establish that the underlying stub method was called. @@ -16801,7 +14997,9 @@ def test_purge_products_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + with mock.patch.object( + type(client.transport.purge_products), + '__call__') as call: client.purge_products(request=None) # Establish that the underlying stub method was called. @@ -16822,13 +15020,12 @@ def test_product_search_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.AbstractOperationsClient, +operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client - def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ProductSearchClient( @@ -16839,21 +15036,18 @@ def test_transport_grpc_default(): transports.ProductSearchGrpcTransport, ) - def test_product_search_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProductSearchTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_product_search_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport.__init__" - ) as Transport: + with mock.patch('google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport.__init__') as Transport: Transport.return_value = None transport = transports.ProductSearchTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -16862,25 +15056,25 @@ def test_product_search_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "create_product_set", - "list_product_sets", - "get_product_set", - "update_product_set", - "delete_product_set", - "create_product", - "list_products", - "get_product", - "update_product", - "delete_product", - "create_reference_image", - "delete_reference_image", - "list_reference_images", - "get_reference_image", - "add_product_to_product_set", - "remove_product_from_product_set", - "list_products_in_product_set", - "import_product_sets", - "purge_products", + 'create_product_set', + 'list_product_sets', + 'get_product_set', + 'update_product_set', + 'delete_product_set', + 'create_product', + 'list_products', + 'get_product', + 'update_product', + 'delete_product', + 'create_reference_image', + 'delete_reference_image', + 'list_reference_images', + 'get_reference_image', + 'add_product_to_product_set', + 'remove_product_from_product_set', + 'list_products_in_product_set', + 'import_product_sets', + 'purge_products', ) for method in methods: with pytest.raises(NotImplementedError): @@ -16896,7 +15090,7 @@ def test_product_search_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -16905,33 +15099,26 @@ def test_product_search_base_transport(): def test_product_search_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.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id="octopus", ) def test_product_search_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.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" - ) as Transport: + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport() @@ -16940,15 +15127,15 @@ def test_product_search_base_transport_with_adc(): def test_product_search_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) ProductSearchClient() adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), quota_project_id=None, ) @@ -16963,15 +15150,12 @@ def test_product_search_auth_adc(): def test_product_search_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: + 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", - "https://www.googleapis.com/auth/cloud-vision", - ), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-vision',), quota_project_id="octopus", ) @@ -16985,38 +15169,39 @@ def test_product_search_transport_auth_adc(transport_class): ], ) def test_product_search_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + 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: + 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 - ) + 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) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.ProductSearchGrpcTransport, grpc_helpers), - (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_product_search_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( + 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"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "vision.googleapis.com:443", @@ -17024,9 +15209,9 @@ def test_product_search_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ), + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-vision', +), scopes=["1", "2"], default_host="vision.googleapis.com", ssl_credentials=None, @@ -17037,14 +15222,10 @@ def test_product_search_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -17053,7 +15234,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -17074,77 +15255,61 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + 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 + certificate_chain=expected_cert, + private_key=expected_key ) - def test_product_search_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.ProductSearchRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ProductSearchRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_product_search_host_no_port(transport_name): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com" + 'vision.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_product_search_host_with_port(transport_name): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vision.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='vision.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "vision.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://vision.googleapis.com:8000" + 'vision.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://vision.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_product_search_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -17213,10 +15378,8 @@ def test_product_search_client_transport_session_collision(transport_name): session1 = client1.transport.purge_products._session session2 = client2.transport.purge_products._session assert session1 != session2 - - def test_product_search_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ProductSearchGrpcTransport( @@ -17229,7 +15392,7 @@ def test_product_search_grpc_transport_channel(): def test_product_search_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.ProductSearchGrpcAsyncIOTransport( @@ -17244,20 +15407,12 @@ def test_product_search_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_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: +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_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 @@ -17266,7 +15421,7 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -17296,23 +15451,17 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport # 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.ProductSearchGrpcTransport, - transports.ProductSearchGrpcAsyncIOTransport, - ], -) -def test_product_search_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.ProductSearchGrpcTransport, transports.ProductSearchGrpcAsyncIOTransport]) +def test_product_search_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: + 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() @@ -17343,7 +15492,7 @@ def test_product_search_transport_channel_mtls_with_adc(transport_class): def test_product_search_grpc_lro_client(): client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) transport = client.transport @@ -17360,7 +15509,7 @@ def test_product_search_grpc_lro_client(): def test_product_search_grpc_lro_async_client(): client = ProductSearchAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport='grpc_asyncio', ) transport = client.transport @@ -17378,11 +15527,7 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( - project=project, - location=location, - product=product, - ) + expected = "projects/{project}/locations/{location}/products/{product}".format(project=project, location=location, product=product, ) actual = ProductSearchClient.product_path(project, location, product) assert expected == actual @@ -17399,18 +15544,11 @@ def test_parse_product_path(): actual = ProductSearchClient.parse_product_path(path) assert expected == actual - def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = ( - "projects/{project}/locations/{location}/productSets/{product_set}".format( - project=project, - location=location, - product_set=product_set, - ) - ) + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format(project=project, location=location, product_set=product_set, ) actual = ProductSearchClient.product_set_path(project, location, product_set) assert expected == actual @@ -17427,21 +15565,13 @@ def test_parse_product_set_path(): actual = ProductSearchClient.parse_product_set_path(path) assert expected == actual - def test_reference_image_path(): project = "squid" location = "clam" product = "whelk" reference_image = "octopus" - expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( - project=project, - location=location, - product=product, - reference_image=reference_image, - ) - actual = ProductSearchClient.reference_image_path( - project, location, product, reference_image - ) + expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format(project=project, location=location, product=product, reference_image=reference_image, ) + actual = ProductSearchClient.reference_image_path(project, location, product, reference_image) assert expected == actual @@ -17458,12 +15588,9 @@ def test_parse_reference_image_path(): actual = ProductSearchClient.parse_reference_image_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = ProductSearchClient.common_billing_account_path(billing_account) assert expected == actual @@ -17478,12 +15605,9 @@ def test_parse_common_billing_account_path(): actual = ProductSearchClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = ProductSearchClient.common_folder_path(folder) assert expected == actual @@ -17498,12 +15622,9 @@ def test_parse_common_folder_path(): actual = ProductSearchClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = ProductSearchClient.common_organization_path(organization) assert expected == actual @@ -17518,12 +15639,9 @@ def test_parse_common_organization_path(): actual = ProductSearchClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = ProductSearchClient.common_project_path(project) assert expected == actual @@ -17538,14 +15656,10 @@ def test_parse_common_project_path(): actual = ProductSearchClient.parse_common_project_path(path) assert expected == actual - def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = ProductSearchClient.common_location_path(project, location) assert expected == actual @@ -17565,18 +15679,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.ProductSearchTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ProductSearchTransport, '_prep_wrapped_messages') as prep: client = ProductSearchClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.ProductSearchTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.ProductSearchTransport, '_prep_wrapped_messages') as prep: transport_class = ProductSearchClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -17587,11 +15697,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -17600,11 +15709,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ProductSearchAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -17612,11 +15720,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -17624,12 +15731,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = ProductSearchClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -17638,14 +15746,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (ProductSearchClient, transports.ProductSearchGrpcTransport), - (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (ProductSearchClient, transports.ProductSearchGrpcTransport), + (ProductSearchAsyncClient, transports.ProductSearchGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -17660,9 +15764,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None,